-
-
Save maauso/98188b8cf979241a4048f1e138442b06 to your computer and use it in GitHub Desktop.
HaProxy zero downtime reload.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
exec 2>&1 | |
export PIDFILE="/tmp/haproxy.pid" | |
addFirewallRules() { | |
IFS=',' read -ra ADDR <<< "$PORTS" | |
for i in "${ADDR[@]}"; do | |
iptables -w -I INPUT -p tcp --dport $i --syn -j DROP | |
done | |
} | |
removeFirewallRules() { | |
IFS=',' read -ra ADDR <<< "$PORTS" | |
for i in "${ADDR[@]}"; do | |
while iptables -w -D INPUT -p tcp --dport $i --syn -j DROP 2>/dev/null; do :; done | |
done | |
} | |
reload() { | |
echo "Reloading haproxy" | |
( | |
flock 200 | |
# Begin to drop SYN packets with firewall rules | |
addFirewallRules | |
# Wait to settle | |
sleep 0.1 | |
# Save the current HAProxy state | |
socat /var/run/haproxy/socket - <<< "show servers state" > /var/state/haproxy/global | |
# Trigger reload | |
LATEST_HAPROXY_PID=$(cat $PIDFILE) | |
haproxy -p $PIDFILE -f /haproxy.cfg -D -sf $LATEST_HAPROXY_PID 200>&- | |
if [ -n "${HAPROXY_RELOAD_SIGTERM_DELAY-}" ]; then | |
sleep $HAPROXY_RELOAD_SIGTERM_DELAY && kill $LATEST_HAPROXY_PID 200>&- 2>/dev/null & | |
fi | |
# Remove the firewall rules | |
removeFirewallRules | |
# Need to wait 1s to prevent TCP SYN exponential backoff | |
sleep 1 | |
) 200>/var/run/haproxy/lock | |
} | |
mkdir -p /var/state/haproxy | |
mkdir -p /var/run/haproxy | |
reload | |
trap reload SIGHUP | |
while true; do sleep 0.5; done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment