暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

一个发送MHA故障切换通知的Perl脚本

171

小编在前篇中介绍过MHA可以自动处理主库故障切换,文中提到我们可以配置report_script扩展脚本,在故障切换的关键节点发送通知(如邮件、企业微信、钉钉),同步切换进度和结果。

本文将分析一个report_script脚本示例,将MHA故障切换事件推送到钉钉机器人,实现简单的消息通知。

mha_report_dingding.pl

#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
use Getopt::Long;
use LWP::UserAgent;
use JSON;

# -----------------------------
# 解析 MHA 默认参数
# -----------------------------
my ($orig_master, $new_master, $new_slaves, $conf, $subject, $body);
GetOptions(
    "orig_master_host=s" => \$orig_master,
    "new_master_host=s"  => \$new_master,
    "new_slave_hosts=s"  => \$new_slaves,
    "conf=s"             => \$conf,
    "subject=s"          => \$subject,
    "body=s"             => \$body,
);

# 设置事件类型和时间
my $event = $subject || "failover";
my $time  = scalar localtime;

# -----------------------------
# 钉钉机器人 webhook(替换为你的 AccessToken)
# -----------------------------
my $webhook = "https://oapi.dingtalk.com/robot/send?access_token=YOUR_ACCESS_TOKEN";

# -----------------------------
# 构建 Markdown 消息
# -----------------------------
my $msg = <<"END_MSG";
### 【MHA Event】
- **事件类型**: $event
- **旧主库**: $orig_master
- **新主库**: $new_master
- **时间**: $time
END_MSG

# -----------------------------
# 构建 JSON payload
# -----------------------------
my $payload = encode_json({
    msgtype  => "markdown",
    markdown => {
        title => "MHA Event: $event",
        text  => $msg,
    },
});

# -----------------------------
# 发送钉钉通知
# -----------------------------
my $ua = LWP::UserAgent->new;
$ua->timeout(5);
my $res = $ua->post(
    $webhook,
    'Content-Type' => 'application/json;charset=utf-8',
    Content        => $payload
);

if ($res->is_success) {
    print"DingTalk notification sent successfully.\n";
} else {
    warn "Failed to send DingTalk notification: " . $res->status_line . "\n";
}

exit 0;


脚本的主要功能:

  • 接收MHA参数:原主库、新主库、新从库等信息。
  • 构建消息内容
  • 发送钉钉通知

安装依赖

# RHEL/CentOS/Rocky
# perl-LWP-Protocol-https 用于支持 HTTPS 协议调用钉钉接口。
yum install perl-libwww-perl perl-JSON -y
yum install perl-LWP-Protocol-https -y

配置MHA使用

编辑MHA配置文件/etc/mha/app1.cnf:

report_script=/usr/local/bin/mha_report_dingding.pl

重启MHA Manager:

systemctl restart mha_manager

测试脚本

# 执行测试命令(模拟 failover)
/usr/local/bin/mha_report_dingding.pl \
  --orig_master_host=10.10.xxx.xxx \
  --new_master_host=10.10.xxx.xxx \
  --new_slave_hosts=10.10.xxx.xxx,10.10.xxx.xxx \
  --subject=failover \
  --body="MHA detected master failure, promoted 10.10.xxx.xxx as new master"


文章转载自PostgreSQL运维技术,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论