Haproxy

HAproxy:在健康檢查更改時執行腳本

  • October 22, 2019

我已經設置了一個帶有兩個伺服器的後端的 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

現在,當伺服器再次出現故障時,我會通過電子郵件收到通知。我想要歸檔的是在伺服器啟動時啟動一個本地 bash 腳本,而在伺服器關閉時啟動另一個腳本。

那怎麼可能呢?

我可能會使用外部檢查腳本來執行此操作,並使用它來控制上升和下降值。然後,當您遇到上升或下降值時,您可以執行自己的腳本。將您的 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/

引用自:https://serverfault.com/questions/883531