LoginSignup
3
0

PostgreSQL + repmgr Event notificationsの使い方

Last updated at Posted at 2024-03-11

はじめに

repmgrのイベントに応じて、任意のスクリプトを実行する方法を紹介します。

PostgreSQLの検証を行っていて複数のHAツールを検証していましたが、特にこのイベント毎に任意のスクリプトを実行する機能が非常に柔軟性があり、便利な機能でした。

repmgrとは?

まず、repmgrとは、PostgreSQLのクラスタのレプリケーション、及び、フェイルオーバーを管理するためのオープンソースソフトウェア(OSS)となります。
repmgr自体の紹介は他のブログや以下の公式HPをご覧ください。

環境

前提となる環境は以下の通りです。
primary 1台 + standby 1台の最もシンプルな構成を想定しています。

# Version
OS Rocky Linux 8.9
DB PostgreSQL 15.4
HA repmgr 5.3.3

Event notifications

repmgrにはEvent notificaitonsという機能があります。

これは、repmgr、及び、repmgrdが内部的に生成するイベントを通知することが出来る機能です。
Event notificationsを有効にするには、repmgrの設定ファイルであるrepmgr.confに「event_notifications」と「event_notification_command」を設定します。

event_notification_command='/path_to_script/sample_tool -event_type=%e'
event_notifications='standby_promote'

例えば、上記の設定例の場合、standby_promoteイベントが生成された場合に、任意のスクリプトであるsample_toolを実行する、という設定になります。
※引数に渡している-event_type=%eに関しては後述の説明をご覧ください。

Event notificationsの引数

Event notificationsにはいくつかの引数を渡す機能が用意されています。
以下は全てのイベントに対して設定される引数です。

引数 説明
%n node ID
%e event type
%s success (1) or failure (0)
%t timestamp
%d details

また、特定のイベント時のみ設定される引数もあります。

引数 説明 設定されるイベント
%p node ID of the current primary repmgr standby register, repmgr standby follow
node ID of the demoted primary repmgr standby switchover
node ID of the former primary repmgrd_failover_promote
%c conninfo string of the primary repmgr standby register, repmgr standby follow
%a name of the current primary node repmgr standby register, repmgr standby follow

上の設定例では、任意のスクリプト(sample_tool)が-event_type引数を取り、それに%eを渡しています。
%eには、repmgrが生成するイベント名(standby_promote)が渡されます。
従って、以下のように任意のスクリプト側でevent_type毎に処理を書いておけば、イベント毎の処理が実装出来ます。

if event_type=="standby_promote" {
    処理内容
}

※golangで記載した場合の例です。

検証 event_notificationsの引数を出力

イメージしやすいように、実際に以下の通り設定した場合、どのように出力されるのか確認してみます。
standby_promoteイベント発生時に、どのイベント発生時でも渡される引数(%n %e %s %t %d)を、改行を入れて表示しています。

event_notifications='standby_promote'
event_notification_command='echo -e "node_id=%n\nevent_type=%e\nsuccess_or_failure=%s\ntimestamp=%t\ndetails=%d" >> /tmp/notification_command.log 2>&1'

notification_command.logを表示します。

cat /tmp/notification_command.log
node_id=2
event_type=standby_promote
success_or_failure=1
timestamp=2024-02-29 20:13:12.371955+09
details=server "node2" (ID: 2) was successfully promoted to primary

上記の通り、引数がちゃんと渡されている事が確認できました。

さいごに

イベント毎に任意の処理が実行できますので、例えば、以下のように活用する事が考えられます。自分の要件に応じて柔軟に実装出来ますので、是非、お試しください。

  • standby_promoteイベントが発生するとe-mailを送付する
  • standby_promoteイベントが発生したらDNSのAレコードをNewPrimaryに書き換える
  • child_node_disconnectイベントが発生したら同期レプリケーションから非同期レプリケーションに切り替える
  • child_node_reconnectイベントが発生したら同期レプリケーションに戻す

参考

https://www.repmgr.org/
https://www.repmgr.org/docs/5.3/event-notifications.html

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0