HAproxy:在运行状况检查更改时运行脚本

mr.*_*ski 6 healthcheck haproxy alert

我已经设置了一个 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 haproxy@example.com
        email-alert to ops@example.com
Run Code Online (Sandbox Code Playgroud)

现在,当服务器出现故障并再次启动时,我会通过电子邮件收到通知。我想要存档的是在服务器启动时启动本地 bash 脚本,在服务器关闭时启动另一个本地 bash 脚本。

怎么可能呢?

小智 6

我可能会使用外部检查脚本来执行此操作,并使用它来控制上升和下降值。然后,当您遇到上升或下降值时,您可以运行自己的脚本。将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
Run Code Online (Sandbox Code Playgroud)

然后作为外部 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
Run Code Online (Sandbox Code Playgroud)

你也许也可以用 lua 来做到这一点,但我还没有看过。我已经为电子邮件警报做了一些其他选项,例如轮询统计套接字或黑客 haproxy,这些选项可以进行调整,但外部检查可能在这里效果最好。但是,如果您想尝试一下,可以在这里找到它们https://www.loadbalancer.org/blog/3-ways-to-send-haproxy-health-check-email-alerts/