我已经设置了一个 haproxy 配置,其后端有两台服务器,如下所示:
...
default
option log-health-checks
...
mailers mta
mailer smtp1 127.0.0.1:25
...
backend s_api
balance roundrobin
option httpchk GET /sites?site=q&limit=1
http-check expect rstatus (2|3)[0-9][0-9]
server s1_a 1.2.3.4:3600 check inter 5s fall 4 rise 1
server s2_b 1.2.3.5:3600 check backup
timeout queue 60s
timeout server 60s
timeout connect 60s
email-alert mailers mta
email-alert level notice
email-alert from [email protected]
email-alert to [email protected]
现在,当服务器宕机并恢复时,我会通过电子邮件收到通知。我想要存档的是,当服务器恢复时启动一个本地 bash 脚本,当服务器宕机时启动另一个脚本。
这怎么可能呢?
答案1
我可能会使用外部检查脚本来执行此操作,并使用它来控制上升和下降值。然后,当您达到上升或下降值时,您可以运行自己的脚本。将 haproxy 配置中的上升和下降设置为 1,并将检查更改为外部
external-check command ping.sh
server s1_a 1.2.3.4:3600 check inter 5s fall 1 rise 1
server s2_b 1.2.3.5:3600 check backup
timeout queue 60s
timeout server 60s
timeout connect 60s
然后作为一个粗略的例子,使用外部 ping 检查
#!/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
# Set the maximum time in seconds to allow ping to run, 1-10 is a sensible range.
TMEOUT=1
# Interval between pings in seconds, 0.2-1 is a sensible range.
INT=1
# Number of pings to send.
NUM=1
RIP=$(echo ${3}))
VIP=$(echo ${1})
#Optionally provides source IP for Ping
SRC=
if [ "$SRC" != '' ]; then
SRC_IP="-I $SRC"
fi
if ping ${SRC_IP} -n -w${TMEOUT} -i${INT} -c${NUM} ${RIP} >& /dev/null; then
COUNTER="$(cat count)"
if [COUNTER != 0]; then
//run up script here
fi
echo 0 >> count
exit ${?}
else
COUNTER="$(cat count)"
if [COUNTER >= 3]; then
//run down script here
fi
COUNTER=$[COUNTER + 1]
echo COUNTER >> count
exit ${?}
fi
您也可以使用 lua 来执行此操作,但我没有研究过。我为电子邮件警报做了几个其他选项,例如轮询统计套接字或黑客攻击 haproxy,这些选项可以进行调整,但外部检查可能在这里效果最好。但是,如果您想尝试它们,可以在这里找到它们https://www.loadbalancer.org/blog/3-ways-to-send-haproxy-health-check-email-alerts/。