:>/dev/null

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

MySQL+groonga+mroonga構築手順

オンプレ環境でMySQL+groonga+mroonga構成を検証する機会があり、Versionは古いが知見として作業記録メモを残す。
MySQLからgroongaをストレージエンジンとして利用する場合、mroonga plugin(MySQL組込)を使用するが直接利用するケースとの違いを参考資料として共有。

  • 以下構築要件
    • OS:CentOS6.9 x86_84
    • MySQL:5.1.60
    • groonga:2.1.0
    • mroonga:2.1.0

■ 前提

MYSQLからgroongaをストレージエンジンとして使用する場合、下記パターンがあります。

① MySQLからmroongaプラグイン経由(MySQL組込)で利用する場合  
INSTALL PLUGIN groonga SONAME 'ha_mroonga.so';
mysql> show engines; →「mroonga」が表示
テーブルスキーマで「ENGINE=mroonga」指定

② MySQLから直接groongaを利用する場合
INSTALL PLUGIN groonga SONAME 'ha_groonga.so';
mysql> show engines; →「groonga」が表示
テーブルスキーマで「ENGINE=groonga」指定

Mroonga(Groonga)ストレージエンジンでのバックアップに関して

Groonga族のMroongaでのバックアップは、それぞれのRDBMSの仕組みに乗るのがよい。それぞれトランザクションレプリケーションがある。
また、MySQLの場合、InnoDBレプリケーション先としてMroongaを選ぶことができる。こうすると、(データが守られやすい)InnoDBをマスターデータとして考えることができる。

上記記載からInnoDB同様の扱いで問題ないとの認識

ref)
https://diary.kitaitimakoto.net/2016/01/15.html

■ インストール&設定

● 必要な開発ツールインストール

# yum groupinstall "Development Tools"
# yum install openssl openssl-devel readline-devel zlib-devel curl-devel libyaml-devel flex libxml2-devel zlib-devel libpng-devel libjpeg-devel libXpm-devel freetype freetype-devel

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

# wget https://downloads.mysql.com/archives/get/file/MySQL-client-5.1.60-1.glibc23.x86_64.rpm
# wget https://downloads.mysql.com/archives/get/file/MySQL-devel-5.1.60-1.glibc23.x86_64.rpm
# wget https://downloads.mysql.com/archives/get/file/MySQL-server-5.1.60-1.glibc23.x86_64.rpm
# wget https://downloads.mysql.com/archives/get/file/MySQL-shared-5.1.60-1.glibc23.x86_64.rpm
# rpm -ivh MySQL-*
# rpm -qa |grep mysql

※依存関係でエラーが発生した場合、既存のライブラリ削除

# yum remove mysql-libs

● groonga/mroonga インストール

# wget http://dev.mysql.com/get/Downloads/MySQL-5.1/mysql-5.1.60.tar.gz
# tar zxvf mysql-5.1.60.tar.gz
# wget http://packages.groonga.org/source/groonga/groonga-2.1.0.tar.gz
# tar zxvf groonga-2.1.0.tar.gz
# cd groonga-2.1.0
# ./configure
# make
# make install
# groonga --version

# cd ..
# wget http://packages.groonga.org/source/mroonga/mroonga-2.10.tar.gz
# tar zxvf mroonga-2.10.tar.gz
# cd mroonga-2.10
# ./configure PKG_CONFIG_PATH=/usr/local/lib/pkgconfig/ --with-mysql-source=/usr/local/src/mysql-5.1.60 --with-mysql-config=/usr/bin/mysql_config
# make
# make install
# find / -name ha_mroonga.so

● /etc/my.cnf作成

# cp /usr/local/src/mysql-5.1.60/mysql-test/include/default_my.cnf /etc/my.cnf
# vi /etc/my.cnf
...任意内容にて作成...

# /etc/init.d/mysql restart

MySQLにpluginを組み込む

# mysql -uroot -p

mysql> INSTALL PLUGIN groonga SONAME 'ha_groonga.so';
mysql> INSTALL PLUGIN mroonga SONAME 'ha_mroonga.so';
mysql> SHOW engines; (Engineのリストに「mroonga」という項目が追加されていればインストール成功です。)

※UDF関数を登録します。
mysql> CREATE FUNCTION last_insert_grn_id RETURNS INTEGER SONAME 'ha_mroonga.so';
mysql> CREATE FUNCTION mroonga_snippet RETURNS STRING SONAME 'ha_mroonga.so';
mysql> CREATE FUNCTION mroonga_command RETURNS STRING SONAME 'ha_mroonga.so';

+------------+---------+----------------------------------------------------------------+--------------+------+------------+
| Engine     | Support | Comment                                                        | Transactions | XA   | Savepoints |
+------------+---------+----------------------------------------------------------------+--------------+------+------------+
...snip...
| groonga    | YES     | CJK-ready fulltext search, column store                        | NO           | NO   | NO         |
| mroonga    | YES     | CJK-ready fulltext search, column store                        | NO           | NO   | NO         |
...snip...
+------------+---------+----------------------------------------------------------------+--------------+------+------------+

※または下記で確認可能
# mroongaという行があれば期待通りです
$ mysql -uroot -p -e "SHOW PLUGINS"
+------------+----------+----------------+---------------+---------+
| Name       | Status   | Type           | Library       | License |
+------------+----------+----------------+---------------+---------+
...snip...
| mroonga    | ACTIVE   | STORAGE ENGINE | ha_mroonga.so | GPL     |
...snip...
+------------+----------+----------------+---------------+---------+

■ 障害対応

# /etc/init.d/mysql stop
Shutting down MySQL. ERROR! Manager of pid-file quit without updating file.

# 上記エラー発生しmysql停止が出来ない場合、groonga pluginが原因
$ mysql -uroot -p -e "SHOW PLUGINS"
+------------+----------+----------------+---------------+---------+
| Name       | Status   | Type           | Library       | License |
+------------+----------+----------------+---------------+---------+
...snip...
| groonga    | ACTIVE   | STORAGE ENGINE | ha_groonga.so | GPL     |
| mroonga    | ACTIVE   | STORAGE ENGINE | ha_mroonga.so | GPL     |
...snip...
+------------+----------+----------------+---------------+---------+

※不要なgroonga pluginを削減
mysql> UNINSTALL PLUGIN groonga;

これで起動/停止が正常稼働する。

参考)
stop時のエラーに関してはログ(***.err)に下記が記載される。

190708 12:14:43 [Note] Event Scheduler: Purging the queue. 0 events 190708 12:14:43 - mysqld got signal 11 ; This could be because you hit a bug. It is also possible that this binary or one of the libraries it was linked against is corrupt, improperly built, or misconfigured. This error can also be caused by malfunctioning hardware. We will try our best to scrape up some info that will hopefully help diagnose the problem, but since we have already crashed, something is definitely wrong and this may fail.

key_buffer_size=8384512 read_buffer_size=131072 max_used_connections=0 max_threads=151 threads_connected=0 It is possible that mysqld could use up to key_buffer_size + (read_buffer_size + sort_buffer_size)*max_threads = 338325 K bytes of memory Hope that's ok; if not, decrease some variables in the equation.

Thread pointer: 0x0 Attempting backtrace. You can use the following information to find out where mysqld died. If you see no messages after this, something went terribly wrong... stack_bottom = (nil) thread_stack 0x40000 /usr/sbin/mysqld(my_print_stacktrace+0x2e)[0x852ebe] /usr/sbin/mysqld(handle_segfault+0x34c)[0x5c951c] /lib64/libpthread.so.0[0x374f00f7e0] /usr/local/lib/libgroonga.so.0(grn_io_segment_alloc+0x26)[0x7fd07bd1aa56] /usr/local/lib/libgroonga.so.0(grn_hash_get_value+0x20d)[0x7fd07bcea65d] /usr/local/lib/libgroonga.so.0(grn_plugin_close+0x35)[0x7fd07bd75dc5] /usr/local/lib/libgroonga.so.0(grn_obj_close+0x277)[0x7fd07bc5b0f7] /usr/local/lib/libgroonga.so.0(grn_db_close+0xe1)[0x7fd07bc5acc1] /usr/local/lib/libgroonga.so.0(grn_obj_close+0x19c)[0x7fd07bc5b01c] /usr/lib64/mysql/plugin/ha_groonga.so(+0x181de)[0x7fd0802b01de] /usr/sbin/mysqld(Z22ha_finalize_handlertonP13st_plugin_int+0x74)[0x6a0784] /usr/sbin/mysqld[0x71b482] /usr/sbin/mysqld[0x71cd5e] /usr/sbin/mysqld(Z15plugin_shutdownv+0x12a)[0x71d21a] /usr/sbin/mysqld[0x5c990c] /usr/sbin/mysqld(_Z10unireg_endv+0xe)[0x5c9b7e] /usr/sbin/mysqld(kill_server_thread+0x31d)[0x5cbc3d] /lib64/libpthread.so.0[0x374f007aa1] /lib64/libc.so.6(clone+0x6d)[0x374ece8bcd] The manual page at http://dev.mysql.com/doc/mysql/en/crashing.html contains information that should help you find out what is causing the crash.

ref)
mroomga pluginに関して
http://y-ken.hatenablog.com/entry/mroonga-create-function

MySQL(Q4M) + DRBD + HA(Pacemaker/corosync) 構築手順 (障害対応/復旧手順編)

先行の記事(https://ogugu.hateblo.jp/entry/2019/07/02/121645)で構築完了したが、日々の運用で発生した障害対応を行った時の情報を知見として作業記録メモを残す。
HA / DRBD(冗長化)構築に伴い、障害対応時の確認事項が多い為、参考資料として共有。

  • 以下構築要件
    • 先行の記事参照

■ 障害状況

# crm_mon
Last updated: Fri Jun 21 17:05:18 2019
Last change: Fri Jun 21 16:26:10 2019
Stack: corosync
Current DC: drbd01 (176359015) - partition with quorum
Version: 1.1.12-561c4cf
2 Nodes configured
3 Resources configured


Online: [ drbd01 drbd02 ]

Full list of resources:

 Master/Slave Set: ms-drbd_data [drbd_data]
     Masters: [ drbd01 ]
     Slaves: [ drbd02 ]
fs_data (ocf::heartbeat:Filesystem):    Started drbd01

Node Attributes:
* Node drbd01:
    + master-drbd_data                  : 10000
    + ringnumber_0                      : 10.131.6.103 is UP
* Node drbd02:
    + master-drbd_data                  : 1000
    + ringnumber_0                      : 10.131.6.175 is UP

Operations:
* Node drbd02:    fs_data: migration-threshold=1 fail-count=1 last-failure='Fri Jun 21 16:49:09 2019'    + (17) monito

■ 両ノードがStandAlone状態

drbd01がプライマリ-(ro:Primary),drbd02がセカンダリー(ro:Secondary)となっており、csのステータスがどちらも「cs:StandAlone」となっていれば確認は完了です。
もし、どちらかのcsのステータスが接続待ち状態であることを示す「cs:WFConnection」となっていたら、cs:WFConnectionとなっているサーバで以下の切断コマンドを実行して、「StandAlone」に戻します。

# drbdadm disconnect r0

「cat /proc/drbd」コマンドを再実行して、ステータスが「cs:StandAlone」に変わったことを確認できれば準備は完了です。

drbd02のデータを破棄します。

# drbdadm -- --discard-my-data connect r0 

csのステータスが「cs: WFConnection」、roのステータスが「ro:Secondary」となったことを確認します。データを破棄したことによって、drbd02はスタンドアロン状態から「(drbd01との)接続待ち」状態に変更されました。

drbd01の状態がcsのステータスは「cs:StandAlone」、roのステータスは「ro:Primary」となっている事を確認したら、drbd01でDRBD接続コマンドを実行します。

# drbdadm connect r0 

接続コマンドを実行すると、drbd01は以下の状態に変わります。

# cat /proc/drbd 
 
version: 8.4.8-1 (api:1/proto:86-101)
GIT-hash: 22b4c802192646e433d3f7399d578ec7fecc6272 build by mockbuild@, 2016-10-13 19:58:26
 0: cs:Connected ro:Primary/Secondary ds:UpToDate/UpToDate C r-----
    ns:2056 nr:0 dw:32790 dr:76120 al:2 bm:0 lo:0 pe:0 ua:0 ap:0 ep:1 wo:f oos:0
 1: cs:SyncSource ro:Primary/Secondary ds:UpToDate/Inconsistent C r-----
    ns:996 nr:0 dw:58900 dr:230731 al:5 bm:0 lo:0 pe:0 ua:0 ap:0 ep:1 wo:f oos:4088
        [===================>] sync'ed:100.0% (4088/5084)K
        finish: 0:00:03 speed: 996 (996) K/sec

DRBD接続コマンド実行後のdrbd01の状態がroのステータスは「ro:Primary/Secondary」に、csのステータスは「Connected」「SyncSource」となり、drbd01は同期元として、drbd02と正しく接続されました。
接続完了と同時に、DRBDでの同期が再実行されます。

※一部引用
https://www.atmarkit.co.jp/ait/articles/1612/16/news015_3.html

◆ 実際の復旧手順

drbd01:secondary側(旧primary)
drbd02:primary側(旧secondary)

・現状ステータス確認

[root@drbd01 ~]# /etc/init.d/drbd status
m:res  cs          ro                 ds                 p       mounted  fstype
0:r0   StandAlone  Secondary/Unknown  UpToDate/DUnknown  r-----

[root@drbd02 ~]# /etc/init.d/drbd status
m:res  cs          ro               ds                 p       mounted  fstype
0:r0   StandAlone  Primary/Unknown  UpToDate/DUnknown  r-----  ext4

・secondary側のDRBDリソースをセカンダリ状態へ変更

[root@drbd01 ~]# drbdadm secondary r0
[root@drbd01 ~]# /etc/init.d/drbd status
m:res  cs          ro                 ds                 p       mounted  fstype
0:r0   StandAlone  Secondary/Unknown  UpToDate/DUnknown  r-----

・secondary側のメタデータを破棄

[root@drbd01 ~]# drbdadm -- --discard-my-data connect r0
[root@drbd01 ~]# /etc/init.d/drbd status
m:res  cs            ro                 ds                 p  mounted  fstype
0:r0   WFConnection  Secondary/Unknown  UpToDate/DUnknown  C

・primary側でステータス確認

[root@drbd02 ~]# /etc/init.d/drbd status
m:res  cs          ro               ds                 p       mounted  fstype
0:r0   StandAlone  Primary/Unknown  UpToDate/DUnknown  r-----  ext4

※Primary側がStandAloneの場合、Primaryへ昇格させる

[root@drbd01 ~]# /etc/init.d/drbd status
m:res  cs          ro                 ds                 p       mounted  fstype
0:r0   StandAlone  Secondary/Unknown  UpToDate/DUnknown  r-----

[root@drbd01 ~]# drbdadm Primary r0
[root@drbd01 ~]# /etc/init.d/drbd status
m:res  cs          ro               ds                 p       mounted  fstype
0:r0   StandAlone  Primary/Unknown  UpToDate/DUnknown  r-----

・primary側で手動再同期

[root@drbd02 ~]#  drbdadm connect r0
[root@drbd02 ~]# /etc/init.d/drbd status
m:res  cs         ro                 ds                 p  mounted  fstype
0:r0   Connected  Primary/Secondary  UpToDate/UpToDate  C  /data    ext4

※自動マウントされてない場合、手動にて実行

# mount -t ext4 /dev/drbd0 /data/

・secondary側ステータス確認

[root@drbd01 ~]# /etc/init.d/drbd status
m:res  cs         ro                 ds                 p  mounted  fstype
0:r0   Connected  Secondary/Primary  UpToDate/UpToDate  C

■ 故障履歴の表示、クリア

・個別リソース

[root@drbd01 ~]# crm resource failcount drbd_data show drbd01
scope=status  name=fail-count-drbd_data value=0
[root@drbd01 ~]# crm resource failcount fs_data show drbd01
scope=status  name=fail-count-fs_data value=0
[root@drbd01 ~]# crm resource cleanup fs_data
Cleaning up fs_data on drbd01
Waiting for 2 replies from the CRMd.. OK
●Master/Slave の障害履歴のクリア

・確認

Online: [ drbd01 drbd02 ]

 Master/Slave Set: ms_res_drbd
     Masters: [ drbd02 ]
     Stopped: [ res_drbd:0 ]
 res_fs (ocf::heartbeat:Filesystem):    Started drbd02

・履歴クリア

[root@drbd02 ~]# crm resource cleanup ms_res_drbd

Online: [ drbd01 drbd02 ]

 Master/Slave Set: ms_res_drbd
     Masters: [ drbd02 ]
     Slaves: [ drbd01 ]
 res_fs (ocf::heartbeat:Filesystem):    Started drbd02

crm コマンドリファレンス

crm configure [リソースの定義]     # リソースの追加
crm configure delete [リソース名]  # リソースの削除
crm configure save backup.crm   # バックアップ
crm configure load update backup.crm   # 外部ファイル読み込み
crm configure show   # 設定内容確認
crm configure erase   # 設定削除

ただし、ノードが「running」ステータスでは下記のようなエラーが発生します。
WARNING: resource IPaddr2_1 is running, can't delete it
WARNING: resource pingd_gw is running, can't delete it
WARNING: resource prmVIPcheck is running, can't delete it
ERROR: CIB erase aborted (nothing was deleted)
その場合は、全ノードを「standby」ステータスに切り替え、「running」ステータス以外にする事が必要です。

crm resource start                # リソースの開始
crm resource stop                 # リソースの停止
crm resource cleanup [リソース名] [ノード名]  # 故障履歴の削除
crm node list                     # ノードの一覧
crm node delete [ノード名]         # ノードの削除
crm node standby server1   # ノードstandby
crm node online server1   # ノードonline

ref)
http://infra.blog.shinobi.jp/Entry/44/
https://hogem.hatenablog.com/entry/20080706/1215341445
https://linux-ha.osdn.jp/wp/archives/1338#i-3

MySQL(Q4M) + DRBD + HA(Pacemaker/corosync) 構築手順 (インストール編)

オンプレ環境でMySQL+DRBD+HA構成を検証する機会があり、クラウド全盛のタイミングだが低レイヤーの知見として作業記録メモを残す。
クラウドのマネージドサービスを使用した場合、クラウドベンダー範疇の為意識されてないが参考資料として共有。
基本となる構成は、サービスを提供する「アクティブサーバ」と、いざという時のために予備機として待機している「スタンバイサーバ」の2台で構成される「アクティブ/スタンバイ」型のHA環境です。

  • 以下構築要件
    • OS:CentOS6.9 x86_84
    • クラスタソフト:Pacemaker 1.1.12 / Corosync 2.3.4
    • データ同期:DRBD8.3.16
    • 制御対象:仮想IP / MySQL
    • 監視用インターフェース:eth1 (eth0はサービス用ポート)

◎ 導入〜動作確認までの手順

■ DRBD構成

パーティション確認

[root@drbd01 ~]# fdisk -l

ディスク /dev/sda: 32.2 GB, 32212254720 バイト
ヘッド 255, セクタ 63, シリンダ 3916
Units = シリンダ数 of 16065 * 512 = 8225280 バイト
セクタサイズ (論理 / 物理): 512 バイト / 512 バイト
I/O size (minimum/optimal): 512 bytes / 512 bytes
ディスク識別子: 0x0008a1d3

デバイス ブート      始点        終点     ブロック   Id  システム
/dev/sda1   *           1          66      524288   83  Linux
パーティション 1 は、シリンダ境界で終わっていません。
/dev/sda2              66         334     2150400   82  Linux スワップ / Solaris
パーティション 2 は、シリンダ境界で終わっていません。
/dev/sda3             334        3917    28781568   83  Linux

ディスク /dev/sdb: 107.4 GB, 107374182400 バイト
ヘッド 255, セクタ 63, シリンダ 13054
Units = シリンダ数 of 16065 * 512 = 8225280 バイト
セクタサイズ (論理 / 物理): 512 バイト / 512 バイト
I/O size (minimum/optimal): 512 bytes / 512 bytes
ディスク識別子: 0x00000000

●epelレポジトリ追加

[root@drbd01 ~]# yum install http://ftp.kddilabs.jp/Linux/RPMS/elrepo/elrepo/el6/x86_64/RPMS/elrepo-release-6-8.el6.elrepo.noarch.rpm

● DRBDインストール

[root@drbd01 ~]# yum install --enablerepo=elrepo drbd83 kmod-drbd83
[root@drbd01 ~]# rpm -qa | grep drbd
drbd83-utils-8.3.16-1.el6.elrepo.x86_64
kmod-drbd83-8.3.16-3.el6.elrepo.x86_64

● /etc/hosts設定

[root@drbd01 ~]vi /etc/hosts
10.131.6.1   drbd01
10.131.6.2   drbd02

● /etc/drbd.confの作成

[root@drbd01 ~]# vi /etc/drbd.conf
# You can find an example in  /usr/share/doc/drbd.../drbd.conf.example

#include "drbd.d/global_common.conf";
#include "drbd.d/*.res";

global {
        usage-count yes;
}

common {
    protocol    C;
    startup {
        degr-wfc-timeout    0;
    }

    net {
        cram-hmac-alg   sha1;
        shared-secret   {shared-secret-key};
    }

    disk {
        on-io-error detach;
    }
    syncer {
        rate    50M;
    }
}
resource r0 {
    on drbd01 {
        device      /dev/drbd0;
        disk        /dev/sdb;
        meta-disk   internal;
        address     10.131.6.1:7788;
    }
    on drbd02 {
        device      /dev/drbd0;
        disk        /dev/sdb;
        meta-disk   internal;
        address     10.131.6.2:7788;
    }
}

※hostsで登録した名称とhostnameが一致しない場合、エラーで起動出来たい為、下記設定行う。

[root@localhost ~]# drbdadm create-md r0
'r0' ignored, since this host (localhost.localdomain) is not mentioned with an 'on' keyword.
[root@localhost ~]# hostname drbd01
[root@localhost ~]# logout

● DRBDのメタデータを初期化

[root@drbd01 ~]# drbdadm create-md r0

Writing meta data...
initializing activity log
NOT initialized bitmap
New drbd meta data block successfully created.
success

自動起動ONにする

[root@drbd01 ~]# chkconfig drbd on
[root@drbd01 ~]# chkconfig --list drbd
drbd            0:off   1:off   2:on    3:on    4:on    5:on    6:off

● DRBDサービス起動

[root@drbd01 ~]# /etc/init.d/drbd start
Starting DRBD resources: [ d(r0) s(r0) n(r0) ]..........
***************************************************************
 DRBD's startup script waits for the peer node(s) to appear.
 - In case this node was already a degraded cluster before the
   reboot the timeout is 0 seconds. [degr-wfc-timeout]
 - If the peer was available before the reboot the timeout will
   expire after 0 seconds. [wfc-timeout]
   (These values are for resource 'r0'; 0 sec -> wait forever)
 To abort waiting enter 'yes' [  12]:yes

.

● DRBDサービス起動後のステータス確認

[root@drbd01 ~]# /etc/init.d/drbd status
drbd driver loaded OK; device status:
version: 8.3.16 (api:88/proto:86-97)
GIT-hash: a798fa7e274428a357657fb52f0ecf40192c1985 build by phil@Build64R6, 2014-11-24 14:51:37
m:res  cs         ro                   ds                         p  mounted  fstype
0:r0   Connected  Secondary/Secondary  Inconsistent/Inconsistent  C

● Primary 昇格と DRBD 同期(drbd01) drbd01 を一時的に Primary へ昇格させます。

[root@drbd01 ~]# drbdadm -- --overwrite-data-of-peer primary r0

● DRBDのステータス確認

[root@drbd01 ~]# /etc/init.d/drbd status
drbd driver loaded OK; device status:
version: 8.3.16 (api:88/proto:86-97)
GIT-hash: a798fa7e274428a357657fb52f0ecf40192c1985 build by phil@Build64R6, 2014-11-24 14:51:37
m:res  cs          ro                 ds                     p  mounted  fstype
0:r0   SyncSource  Primary/Secondary  UpToDate/Inconsistent  C
...    sync'ed:    0.3%               (102116/102396)M

drbd01は"SyncSource"になっていることがわかる。

● DRBDのステータス確認(drbd02)

[root@drbd02 ~]# /etc/init.d/drbd status
drbd driver loaded OK; device status:
version: 8.3.16 (api:88/proto:86-97)
GIT-hash: a798fa7e274428a357657fb52f0ecf40192c1985 build by phil@Build64R6, 2014-11-24 14:51:37
m:res  cs          ro                 ds                     p  mounted  fstype
0:r0   SyncTarget  Secondary/Primary  Inconsistent/UpToDate  C
...    sync'ed:    0.6%               (101856/102396)M

drbd02は"SyncTarget"になっていることがわかる。

● 同期完了後の状態確認
sync'ed: **% が同期の進捗状況。「Inconsistent/UpToDate」ステータスになってる。
同期完了後の状態「UpToDate/UpToDate」が表示される。

[root@drbd03 ~]# /etc/init.d/drbd status
drbd driver loaded OK; device status:
version: 8.3.16 (api:88/proto:86-97)
GIT-hash: a798fa7e274428a357657fb52f0ecf40192c1985 build by phil@Build64R6, 2014-11-24 14:51:37
m:res  cs         ro                 ds                 p  mounted  fstype
0:r0   Connected  Primary/Secondary  UpToDate/UpToDate  C

● DRBD ボリュームのマウント(drbd01)
DRBD ボリュームにファイルシステムを作成します。

[root@drbd01 ~]# mkfs.ext4 /dev/drbd0
mke2fs 1.41.12 (17-May-2010)
Filesystem label=
OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
Stride=0 blocks, Stripe width=0 blocks
6553600 inodes, 26213591 blocks
1310679 blocks (5.00%) reserved for the super user
First data block=0
Maximum filesystem blocks=4294967296
800 block groups
32768 blocks per group, 32768 fragments per group
8192 inodes per group
Superblock backups stored on blocks:
    32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208,
    4096000, 7962624, 11239424, 20480000, 23887872

Writing inode tables: done
Creating journal (32768 blocks): done
Writing superblocks and filesystem accounting information: ^@done

This filesystem will be automatically checked every 29 mounts or
180 days, whichever comes first.  Use tune2fs -c or -i to override.

● DRBDマウントポイント作成(drbd01)

[root@drbd01 ~]# mkdir /data
[root@drbd01 ~]# mount -t ext4 /dev/drbd0 /data/
[root@drbd01 ~]# df -hT
Filesystem     Type   Size  Used Avail Use% Mounted on
/dev/sda3      ext4    27G  2.7G   23G  11% /
tmpfs          tmpfs  1.9G     0  1.9G   0% /dev/shm
/dev/sda1      ext4   488M   39M  425M   9% /boot
/dev/drbd0     ext4    99G   60M   94G   1% /data

● DRBDのステータス確認

[root@drbd01 ~]# /etc/init.d/drbd status
drbd driver loaded OK; device status:
version: 8.3.16 (api:88/proto:86-97)
GIT-hash: a798fa7e274428a357657fb52f0ecf40192c1985 build by phil@Build64R6, 2014-11-24 14:51:37
m:res  cs         ro                 ds                 p  mounted  fstype
0:r0   Connected  Primary/Secondary  UpToDate/UpToDate  C  /data    ext4
■ 動作確認

● 適当なファイルをノードAで作成(primary(drbd01))

[root@drbd01 ~]# echo "DRBD TEST from Node A" > /data/test.txt
[root@drbd01 ~]# cat /data/test.txt
DRBD TEST from Node A

● 一旦、primary→secondaryへ切替

[root@drbd01 ~]# umount /data
[root@drbd01 ~]# drbdadm secondary r0

● drbdのステータス確認

[root@drbd01 ~]# /etc/init.d/drbd status
drbd driver loaded OK; device status:
version: 8.3.16 (api:88/proto:86-97)
GIT-hash: a798fa7e274428a357657fb52f0ecf40192c1985 build by phil@Build64R6, 2014-11-24 14:51:37
m:res  cs         ro                   ds                 p  mounted  fstype
0:r0   Connected  Secondary/Secondary  UpToDate/UpToDate  C

※ここで、一旦ノードB(secondary(drbd02))で作業に切り替える

● ノードBでステータス確認(secondary(drbd02))の為、マウントする

[root@drbd02 ~]# mkdir /data
[root@drbd02 ~]# mount -t ext4 /dev/drbd0 /data/

● drbdのステータス確認(primary側を停止(secondaryへ切替)した為、primaryへ昇格してる)

[root@drbd02 ~]# /etc/init.d/drbd status
drbd driver loaded OK; device status:
version: 8.3.16 (api:88/proto:86-97)
GIT-hash: a798fa7e274428a357657fb52f0ecf40192c1985 build by phil@Build64R6, 2014-11-24 14:51:37
m:res  cs         ro                 ds                 p  mounted  fstype
0:r0   Connected  Primary/Secondary  UpToDate/UpToDate  C  /data    ext4

● ノードA(旧primary(drbd01))で書き込みしたデータの同期確認

[root@drbd02 ~]# cat /data/test.txt
DRBD TEST from Node A

● データ同期確認用にデータ書き込み

[root@drbd02 ~]# echo "DRBD TEST from Node B" >> /data/test.txt

● ノードBをsecondaryへ切替

[root@drbd02 ~]# umount /data
[root@drbd02 ~]# drbdadm secondary r0

● drbdのステータス確認

[root@drbd02 ~]# /etc/init.d/drbd status
drbd driver loaded OK; device status:
version: 8.3.16 (api:88/proto:86-97)
GIT-hash: a798fa7e274428a357657fb52f0ecf40192c1985 build by phil@Build64R6, 2014-11-24 14:51:37
m:res  cs         ro                   ds                 p  mounted  fstype
0:r0   Connected  Secondary/Secondary  UpToDate/UpToDate  C

※ここで、ノードA(primary(drbd01))へ作業を切り替える

● secondary→primaryへ切替

[root@drbd01 ~]# drbdadm primary r0
[root@drbd01 ~]# mount -t ext4 /dev/drbd0 /data/

● ノードB(secondary(drbd02))で書き込みしたデータが正常に同期してるか確認

[root@drbd01 ~]# cat /data/test.txt
DRBD TEST from Node A
DRBD TEST from Node B

● drbdのステータス確認(primaryへ切替してる事を確認)

[root@drbd01 ~]# /etc/init.d/drbd status
drbd driver loaded OK; device status:
version: 8.3.16 (api:88/proto:86-97)
GIT-hash: a798fa7e274428a357657fb52f0ecf40192c1985 build by phil@Build64R6, 2014-11-24 14:51:37
m:res  cs         ro                 ds                 p  mounted  fstype
0:r0   Connected  Primary/Secondary  UpToDate/UpToDate  C  /data    ext4

※ここで、ノードB(secondary(drbd02))へ作業を切り替える

● drbdのステータス確認(primaryが復旧した為、「Secondary/Primary」へ切替済みを確認)

[root@drbd02 ~]# /etc/init.d/drbd status
drbd driver loaded OK; device status:
version: 8.3.16 (api:88/proto:86-97)
GIT-hash: a798fa7e274428a357657fb52f0ecf40192c1985 build by phil@Build64R6, 2014-11-24 14:51:37
m:res  cs         ro                 ds                 p  mounted  fstype
0:r0   Connected  Secondary/Primary  UpToDate/UpToDate  C

● 同期パーティション設定のmountポイントが解除されているか確認

[root@drbd02 ~]# df -hT
Filesystem     Type   Size  Used Avail Use% Mounted on
/dev/sda3      ext4    27G  2.7G   23G  11% /
tmpfs          tmpfs  1.9G     0  1.9G   0% /dev/shm
/dev/sda1      ext4   488M   39M  425M   9% /boot

■ HA構成

● Pacemakerリポジトリを取得、インストール

[root@drbd01 tmp]# wget https://ja.osdn.net/projects/linux-ha/downloads/62369/pacemaker-repo-1.1.12-1.1.el6.x86_64.rpm
[root@drbd01 tmp]# rpm -ivh pacemaker-repo-1.1.12-1.1.el6.x86_64.rpm
[root@drbd01 tmp]# yum install pacemaker-all

● /etc/corosync/corosync.conf設定

[root@drbd01 tmp]# /etc/corosync/corosync.conf

● /etc/corosync/corosync.conf設定

compatibility: whitetank

aisexec {
       user: root
       group: root
}

service {
       name: pacemaker
       ver: 0
       use_mgmtd: yes
}

amf {
       mode: disabled
}

totem {
       version: 2
       secauth: off
       threads: 0
       rrp_mode: none
       clear_node_high_bit: yes
       token: 4000
       censensus: 7000
       join: 60
       interface {
               member {
                       memberaddr: 10.131.6.103    #ノードA
               }
               member {
                       memberaddr: 10.131.6.175    #ノードB
               }
               ringnumber: 0
               bindnetaddr: 10.131.0.0         #ネットワークアドレス
               mcastport: 5405
               ttl: 1
       }
       transport: udpu
}

logging {
       fileline: off
       to_logfile: yes
       to_syslog: no
       logfile: /var/log/cluster/corosync.log
       debug: off
       timestamp: on
       logger_subsys {
               subsys: AMF
               debug: off
       }
}

quorum {
       provider: corosync_votequorum
       expected_votes: 2
       two_node: 1
}

※ Pacemaker/Corosync の設定値について
https://www.sraoss.co.jp/tech-blog/pacemaker/pacemaker-config-values/

自動起動ONにする

[root@drbd01 tmp]# chkconfig pacemaker on
[root@drbd01 tmp]# chkconfig corosync on

● サービス起動
Pacemaker, Corosync起動(初回のみ)
両方のノードで起動する

[root@drbd01 tmp]# /etc/init.d/corosync start
[root@drbd01 tmp]# /etc/init.d/pacemaker start

※ 手動で停止するときはこの順番で停止すること

[root@drbd01 tmp]# /etc/init.d/pacemaker stop
[root@drbd01 tmp]# /etc/init.d/corosync stop

● Pacemakerの起動状態確認(片方のノードで実行すればよい)

[root@drbd01 tmp]# crm_mon -Aro

Last updated: Fri Jun 21 14:49:37 2019
Last change: Fri Jun 21 14:43:01 2019
Stack: corosync
Current DC: drbd03 (176359015) - partition with quorum
Version: 1.1.12-561c4cf
2 Nodes configured
0 Resources configured


Online: [ drbd01 drbd02 ]

Full list of resources:


Node Attributes:
* Node drbd01:
* Node drbd02:

Operations:
* Node drbd01:
* Node drbd02:

CRM設定
片方のノードで実行すればよい

[root@drbd01 tmp]# crm configure
crm(live)configure#
crm(live)configure# property no-quorum-policy=ignore stonith-enabled=false
crm(live)configure# rsc_defaults resource-stickiness=INFINITY migration-threshold=1
crm(live)configure# commit
crm(live)configure# exit

● DRBDを死活監視対象に設定

[root@drbd01 tmp]# crm configure
crm(live)configure# primitive drbd_data ocf:linbit:drbd params drbdconf=/etc/drbd.conf drbd_resource=r0 \
op start interval=0s timeout=240s \
op monitor interval=10 role=Slave \
op monitor interval=11 role=Master \
op stop interval=0 timeout=100s on-fail=block

crm(live)configure# ms ms-drbd_data drbd_data meta notify=true
crm(live)configure# primitive fs_data ocf:heartbeat:Filesystem params run_fsck=no device=/dev/drbd0 directory=/data fstype=ext4 \
op start interval=0s timeout=60s \
op monitor interval=15 timeout=40s \
op stop interval=0 timeout=60s on-fail=ignore

crm(live)configure# colocation coloc-drbd_fs inf: fs_data ms-drbd_data:Master
crm(live)configure# order order-drbd_fs inf: ms-drbd_data:promote fs_data:start

● 設定反映 上記を実行すると設定のみ追加され、まだ登録されていません。
次の内容を実行して、設定を登録反映します。

crm(live)configure# commit
crm(live)configure# exit

● 設定の確認

[root@drbd01 ~]# crm config
crm(live)configure# show
node 176359015: drbd01
node 176359087: drbd02
primitive drbd_data ocf:linbit:drbd \
    params drbdconf="/etc/drbd.conf" drbd_resource=r0 \
    op start interval=0s timeout=240s \
    op monitor interval=10 role=Slave \
    op monitor interval=11 role=Master \
    op stop interval=0 timeout=100s on-fail=block
primitive fs_data Filesystem \
    params run_fsck=no device="/dev/drbd0" directory="/data" fstype=ext4 \
    op start interval=0s timeout=60s \
    op monitor interval=15 timeout=40s \
    op stop interval=0 timeout=60s on-fail=ignore
ms ms-drbd_data drbd_data \
    meta notify=true
colocation coloc-drbd_fs inf: fs_data ms-drbd_data:Master
order order-drbd_fs inf: ms-drbd_data:promote fs_data:start
property cib-bootstrap-options: \
    dc-version=1.1.12-561c4cf \
    cluster-infrastructure=corosync \
    no-quorum-policy=ignore \
    stonith-enabled=false \
    last-lrm-refresh=1561106859
rsc_defaults rsc-options: \
    resource-stickiness=INFINITY \
    migration-threshold=1

● Pacemakerステータス確認

[root@drbd01 tmp]# crm_mon

Last updated: Fri Jun 21 15:46:29 2019
Last change: Fri Jun 21 15:44:25 2019
Stack: corosync
Current DC: drbd01 (176359015) - partition with quorum
Version: 1.1.12-561c4cf
2 Nodes configured
3 Resources configured


Online: [ drbd01 drbd02 ]

 Master/Slave Set: ms-drbd_data [drbd_data]
     Masters: [ drbd01 ]
     Slaves: [ drbd02 ]
fs_data (ocf::heartbeat:Filesystem):    Started drbd01

● 仮想IP作成/ha resources設定
MySQLのリソースの追加
primitive mysqld lsb:mysqld
→「lsb」というのは、Linux Standard Baseの略。Linux標準で提供される/etc/init.d以下にある起動スクリプトのこと

◆ リソースのグループ、リソース間の制約・順序の設定
最後に、リソースのグループ、リソース間の制約(colocation(関連性)・順序の設定する。

group mysql fs_mysql ip_mysql mysqld
colocation mysql_on_drbd inf: mysql ms_drbd_mysql:Master
order mysql_after_drbd inf: ms_drbd_mysql:promote mysql:start

設定の意味は、
1行目は「ファイルシステムと共有IPとMySQLをグループ『mysql』に指定」
2行目は「mysqlグループとDRBDのマスターは同時に存在しなくてはならない」
3行目は「DRBDのマスターが起動した後に、mysqlグループが起動しなくてはならない」

ref)
https://qiita.com/fetaro/items/9a836ed0922c82f53a25

◆ 実際の追加手順

[root@drbd04 ~]# crm config

crm(live)configure# primitive vip1 ocf:heartbeat:IPaddr2 \
params ip=10.131.xxx.xxx nic=eth1 cidr_netmask=24 \
op start interval=0s timeout=20s \
op stop interval=0s timeout=20s \
op monitor interval=30s
crm(live)configure# primitive q4m lsb:q4m
crm(live)configure# group grpora fs_data vip1 q4m
INFO: resource references in colocation:coloc-drbd_fs updated
INFO: resource references in order:order-drbd_fs updated
crm(live)configure# commit
crm(live)configure# exit
  • crm(live)configure# group {グループ名} fs_data vip1 q4m ← groupを作成しリソース追加
  • INFO: resource references in colocation:coloc-drbd_fs updated ← 既存のcolocationに追加
  • INFO: resource references in order:order-drbd_fs updated ← 既存のorderに追加

colocation制約は複数のリソースを同一ノードで起動させる制約として用い、order制約はリソース同士のアクション(起動及び停止など)の順序を指定します。リソースグループは上記の制約を合わせたようなもので、同じリソースグループに指定したリソースは同一ノードで起動され、起動順序も指定されます。

● Pacemakerステータス確認

[root@drbd01 ~]# crm_mon

Last updated: Tue Jun 25 14:14:14 2019
Last change: Tue Jun 25 14:13:47 2019
Stack: corosync
Current DC: drbd01 (176359015) - partition with quorum
Version: 1.1.12-561c4cf
2 Nodes configured
5 Resources configured


Online: [ drbd01 drbd02 ]

 Master/Slave Set: ms-drbd_data [drbd_data]
     Masters: [ drbd01 ]
     Slaves: [ drbd02 ]
 Resource Group: {グループ名}
     fs_data    (ocf::heartbeat:Filesystem):    Started drbd01
     vip1   (ocf::heartbeat:IPaddr2):   Started drbd01
     q4m        (lsb:q4m):  Started drbd01
[lsb経由でのサービス起動に関して]

lsb経由でのリソース起動は下記仕様に準拠し作成する必要がある。

lsb:initスクリプト名 /etc/init.d/initスクリプト名 に配置されたスクリプトをRAとして使用します。 Linuxに付属のinitスクリプトをRAとして使用することができます。 ただし、initスクリプトがLSBと呼ばれる仕様に準拠している必要があります。

▲例:q4mをlsb経由で管理出来るようにinitd起動スクリプト修正
変更前)

...
condrestart(){
    [ -e /var/lock/subsys/q4m ] && restart || :
}

# See how we were called.
case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  status)
    status mysqld
    ;;
  restart)
    restart
    ;;
  condrestart)
    condrestart
    ;;
  *)
    echo $"Usage: $0 {start|stop|status|condrestart|restart}"
    exit 1
esac

exit $?  

変更後)

...
condrestart(){
    [ -e /var/lock/subsys/q4m ] && restart || :
}


function stop_q4m() {
         stop
         return 0
}

function status_q4m() {
        ps -p `cat $mypidfile` > /dev/null 2>&1
        RETVAL=$?
         if [ $RETVAL -eq 0 ] ; then
          return 0
         else
          return 3
         fi
}

function monitor_q4m() {
        ps -p `cat $mypidfile` > /dev/null 2>&1
        RETVAL=$?
         if [ $RETVAL -eq 0 ] ; then
          return 0
         else
          return 3
         fi
}

case $1 in
        start ) start ;;
        stop ) stop_q4m ;;
        status ) status_q4m ;;
        monitor ) monitor_q4m ;;
esac

exit $?

ref)
●インストール方法
http://infra.blog.shinobi.jp/Entry/44/ https://www39.atwiki.jp/th0901/pages/20.html https://hogem.hatenablog.com/entry/20080706/1215341445 https://qiita.com/hkajikawa/items/b911a92365e4a7b70164#%E3%83%87%E3%82%A3%E3%82%B9%E3%82%AF%E3%81%8C%E5%A3%8A%E3%82%8C%E3%81%9F%E6%99%82%E3%81%AE%E5%AF%BE%E5%BF%9C%E3%81%A8%E5%A3%8A%E3%82%8C%E3%81%9F%E3%81%A8%E3%81%8D%E3%81%AE%E5%8B%95%E4%BD%9C%E3%82%92%E7%A2%BA%E8%AA%8D

●pcs を用いたインストール方法
https://knowledge.sakura.ad.jp/19690/
https://centossrv.com/pacemaker_drbd.shtml

crmコマンドに関しては下記サイトがわかりやすい
https://dexlab.net/pukiwiki/index.php?Memo/Linux/Pacemaker

●DRBDエンジニアサイ
https://blog.3ware.co.jp/

crm リソースのメタオプション
https://access.redhat.com/documentation/ja-jp/red_hat_enterprise_linux/6/html/configuring_the_red_hat_high_availability_add-on_with_pacemaker/s1-resourceopts-haar

●lsbに関して
https://linux-ha.osdn.jp/wp/archives/3855#lsb
http://www.kurobuti.com/blog/?p=4667
http://server-helper.doorblog.jp/archives/4142815.html

cloudmapperに入門した

awsの構成変更を行う場合、Document更新を忘れるので良い方法がないか調査した。
本来なら構成変更を行ったタイミングで自動化してDocument更新をするのが良いが効果的な方法が見つからない。
cloudmapperを使用した場合、現時点での構成が図表されるので代替え案として検討した。
導入する為に行った時の勉強メモ。

  • 以下構築要件
    • awsの構成管理を行う(現時点で運用されてる構成図を表示)
    • awsのec2インスタンス上にcloudmapperをインストール
    • cloudmapperをインストールしたインスタンスから各インスタンスへ接続可能
    • cloudmapperをインストールしたインスタンスにグローバルからアクセス可能
      • EIPを割当済みの場合、IP変更が発生せず便利

■下記に導入〜動作確認までを記載する

● OSに必要環境セットアップ

$sudo yum install autoconf automake libtool python3-devel.x86_64 python3-tkinter python34-devel awscli w3m jq
$virtualenv venv
$python --version
$pip install -r requirements.txt

● cloudmapperインストール

$git clone https://github.com/duo-labs/cloudmapper.git

● ユーザーが未作成の場合、コンソールより作成

$aws --profile cloudmapper iam create-user --user-name cloudmapper

● accounts確認

[ec2-user@ip-172-31-xxx-xxx cloudmapper]$ cat config.json
{  "accounts":
    [
        {"id": "123456789012", "name": "aws-account-1", "default": true}
    ],
    "cidrs":
    {
        "1.1.1.1/32": {"name": "SF Office"},
        "2.2.2.2/28": {"name": "NY Office"}
    }
}

● credentialsファイル確認

[ec2-user@ip-172-31-xxx-xxx cloudmapper]$ cat ~/.aws/credentials
[default]
aws_access_key_id = *********
aws_secret_access_key = *********

[cloudmapper]
aws_access_key_id = *********
aws_secret_access_key = *********

● 起動

$cd /home/ec2-user/cloudmapper
$./collect_data.sh --account aws-account-1 --profile cloudmapper
$python cloudmapper.py prepare --account aws-account-1
$python cloudmapper.py webserver --public --port 8001

※ 一部起動パラメータが変更になっているので調整する

$ python cloudmapper.py webserver {args}

def run(arguments):
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
"--port",
help="Port to listen on",default=8000,type=int)
parser.add_argument(
"--public",
dest='is_public',help="Allow connections from 0.0.0.0 (or :: if --ipv6 was provided) as opposed to only localhost",action='store_true')
parser.add_argument(
"--ipv6",
dest='is_ipv6',help="Listen on IPv6",action='store_true')

● 動作確認

$curl http://localhost:8001/
$w3m http://localhost:8001/

以下のように、VPCやSubnetのレイアウトやSecurity Groupによるアクセス許可を可視化できる
(README.mdより引用) f:id:oguguman:20190517164146p:plain

ref)
https://qiita.com/bukaz/items/4a769065cd14b192319f

Ansibleを使用した構成管理に入門した

ansibleを使用して構成管理をする場合の条件分岐方法の調査を行った時の勉強メモ。

  • 以下構築要件
    • Ansibleで構成管理を行う(冪等性の担保)
    • Ansibleで各環境毎に設定内容を書き換える
      • PRD(Production)/STG(Staging)/sandbox等

■下記に各設定サンプルのconfファイルを記載する

  • template/prd.confの設定
<source>
  @id prd_src
  @type   config_expander
  <config>
    @type tail
    @label @{{ td_agent_label }}
    read_from_head true
    path /home/prd/logs/*.log
    pos_file /var/log/td-agent/prd.pos
    format none
    message_key log_line
    tag {{ td_agent_tag }}
  </config>
</source>
  • template/sbx.confの設定
<source>
  @id sbx_src
  @type   config_expander
  <config>
    @type tail
    @label @{{ td_agent_label }}
    read_from_head true
    path /home/sbx/logs/*.log
    pos_file /var/log/td-agent/sbx.pos
    format none
    message_key log_line
    tag {{ td_agent_tag }}
  </config>
</source>
  • template/td-agent.confの設定
{% if is_sandbox %}
@include sbx.conf
{% else %}
@include prd.conf
{% endif %}
  • group_vars/servers.ymlの設定
is_sandbox: True
tdagent_force_restart: False
tdagent_conf_dir: "{{ inventory_dir }}/templates/td-agent"
td_agent_label: test-pjt
td_agent_tag: stage-src-tag
td_agent_loginfo_group: test-grp
tdagent_conf_files:
 - { src: "{{ tdagent_conf_dir }}/td-agent.conf.j2", dest: "td-agent.conf" }
 - { src: "{{ tdagent_conf_dir }}/in.www.nginx.access.conf.j2", dest: "in.www.nginx.access.conf" }
 - { src: "{{ tdagent_conf_dir }}/in.www.nginx.error.conf.j2", dest: "in.www.nginx.error.conf" }
 - { src: "{{ tdagent_conf_dir }}/out.conf.j2", dest: "out.conf" }
tdagent_root_exec: True
  • hostsの設定(inventory)
[all:vars]
ansible_connection=ssh
ansible_user=username
ansible_ssh_pass=userpwd
ansible_sudo_pass=rootpwd

[servers]
vm1234 ansible_host=172.31.100.1 newrelic_install=true
  • servers.ymlの設定(playbook)
---
- hosts: servers
  become: yes
  strategy: free
  become_method: su
  become_user: root
  roles:
    - { role: newrelic, when: "newrelic_install == 'true'" }
  • playbook実行
# ansible-playbook -i hosts -u username servers.yml -K -S --diff

Ansibleを使用した構成管理構成を構築した。
冪等性の担保、コンテナ化した構成管理時に効率的に運用管理が行う事が可能。
CI/CD、デプロイ等を絡めた構成管理が前提の状況な為、知識を確実に体系化する必要がある。

Amazon Kinesis Client Library (KCL)を使用したログ収集基盤構成

Amazon Kinesis Client Library (KCL)を使用したログファイル収集基盤構成を構築する必要があり、調査を行った時の勉強メモ。

  • 以下構築要件

    • apacheaccess_logを集約サーバへ収集する
    • 集約サーバでAmazon Kinesis Client Library (KCL) ライブラリを使用して送信←今回、構築部分
    • KCL → aws kinesis stream へ送信
    • aws kinesis stream → s3/aes等へ送信
      • バックアップ/可視化など
  • KCLの設定

[ec2-user@ip-172-xx-xx-xx aws-kinesis]$ cat agent.json
{
  "awsAccessKeyId": "******",
  "awsSecretAccessKey": "******",
  "cloudwatch.endpoint": "monitoring.ap-northeast-1.amazonaws.com",
  "cloudwatch.emitMetrics": true,
  "kinesis.endpoint": "",
  "firehose.endpoint": "firehose.ap-northeast-1.amazonaws.com",

  "flows": [
    {
      "filePattern": "/tmp/test.log",
      "deliveryStream": "teststream",
      "dataProcessingOptions": [
         {
             "optionName": "LOGTOJSON",
             "logFormat": "COMMONAPACHELOG",
             "matchPattern": "^([\\d.]+) - - \\[([\\w:/]+).*\\] \"(\\w+) /(\\w+).*(\\d.+)\" (\\d{3}) (\\d+) \"(\\S+)\" \"(.*?)\" ([\\d.]+) \"(.*?)\" (\\d+);(\\d+)",
             "customFieldNames": ["client_ip", "time_stamp", "verb", "uri_path", "http_ver", "http_status", "bytes", "referrer", "agent", "response_time", "graphql", "company_id", "user_id"]
         }
      ]
    }
  ]
}
[ec2-user@ip-172-xx-xx-xx ~]$ cat test.sh
#!/bin/bash

start=$(date)
for i in $(seq 1 ${1})
do
    echo ${i}
    echo -e "$( echo $(cat sample.json))" >> /tmp/test.log
    sleep 0.01s
done
echo ${start}
date
  • サンプルデータのフォーマット確認
[ec2-user@ip-172-xx-xx-xx ~]$ cat sample.json
111.111.111.111 - - [02/Dec/2016:13:58:47 +0000] "POST /graphql HTTP/1.1" 200 1161 "https://www.myurl.com/endpoint/12345" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36" 0.172 "query user userMessages hasPermissions F0 F1" 11111;222222

KCL ライブラリを使用したログ収集基盤構成を構築した。
収集時、アグリゲーターでtd-agentを使用した環境と比較し、安易に送信及び構築が可能な為、今後は本環境を使用した基盤構成を行うケースが増えそうです。

aws cloud watchの各使用状況詳細

aws cloudwatchで各使用状況を確認出来るが、各コストに関して詳細に調査する必要があり、調査を行った時の勉強メモ。

  • 請求ダッシュボード -> Cost Explorer ->

    • サービス別の月別使用量ビュー
    • リンクアカウント別の月別使用量ビュー
    • 日別使用量ビュー
      • cost reports
  • 各数値に関して詳細を確認

・Daily total cost
https://console.aws.amazon.com/cost-reports/home?#/custom?groupBy=Service&hasBlended=false&hasAmortized=false&excludeDiscounts=true&excludeTaggedResources=false&timeRangeOption=Custom&granularity=Daily&reportName=&reportType=CostUsage&isTemplate=true&filter=%5B%5D&chartStyle=Group&forecastTimeRangeOption=None&usageAs=usageQuantity&startDate=2018-12-24&endDate=2019-01-18
・有償メトリクス(s3/kinesis shard)
https://console.aws.amazon.com/cost-reports/home?#/custom?groupBy=Operation&hasBlended=false&hasAmortized=false&excludeDiscounts=true&excludeTaggedResources=false&timeRangeOption=Custom&granularity=Daily&reportName=&reportType=CostUsage&isTemplate=true&filter=%5B%7B%22dimension%22:%22Service%22,%22values%22:%5B%22AmazonCloudWatch%22%5D,%22include%22:true,%22children%22:null%7D%5D&chartStyle=Stack&forecastTimeRangeOption=None&usageAs=usageQuantity&startDate=2018-12-30&endDate=2019-01-20

Gourp by : API Operation
Filters > Service : CloudWatch

PutMetricDataの詳細情報取得 -> CloudTrail logにてAPI Callが記録
・Kinesisデータ保持期間
https://console.aws.amazon.com/cost-reports/home?#/custom?groupBy=UsageType&hasBlended=false&hasAmortized=false&excludeDiscounts=true&excludeTaggedResources=false&timeRangeOption=Custom&granularity=Daily&reportName=&reportType=CostUsage&isTemplate=true&filter=%5B%7B%22dimension%22:%22Service%22,%22values%22:%5B%22Amazon%20Kinesis%22%5D,%22include%22:true,%22children%22:null%7D%5D&chartStyle=Stack&forecastTimeRangeOption=None&usageAs=usageQuantity&startDate=2018-12-25&endDate=2019-01-20

Group by : Usage Type
Filters > Service : kinesis

cloud watchを使用したモニタリング環境での各値確認まで完了した。
サーバレスアーキテクチャ等でモニタリング監視を行うケースが増えそうなので確認方法を確立しておく必要ありそうです。