Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Snippet of Unbounce script for restarting HAProxy with zero downtime
echo "Flipping tables! (╯°□°)╯︵ ┻━┻"
num_rules=3
real=3 # exposed to the ELB as port 443
test=4 # used to install test certs for domain verification
health=5 # used by the ELB healthcheck
blue_prefix=855
green_prefix=866
function iptables_status {
blue=$(sudo iptables -t nat -L -n -v | grep REDIRECT | grep ${blue_prefix} | wc -l)
green=$(sudo iptables -t nat -L -n -v | grep REDIRECT | grep ${green_prefix} | wc -l)
if [[ ${blue} == 0 && ${green} == 0 ]]; then
echo "none"
elif [[ ${blue} == ${num_rules} && ${green} == ${num_rules} ]]; then
echo "both"
elif [[ ${blue} == ${num_rules} ]]; then
echo "blue"
elif [[ ${green} == ${num_rules} ]]; then
echo "green"
else
echo "unknown"
fi
}
function add {
instance=$1
instance_prefix="${instance}_prefix"
real_port="${!instance_prefix}${real}"
test_port="${!instance_prefix}${test}"
health_port="${!instance_prefix}${health}"
sudo iptables -t nat -A PREROUTING -m state --state NEW -p tcp --dport 8443 -j REDIRECT --to ${real_port}
sudo iptables -t nat -A PREROUTING -m state --state NEW -p tcp --dport 8444 -j REDIRECT --to ${test_port}
sudo iptables -t nat -A PREROUTING -m state --state NEW -p tcp --dport 8445 -j REDIRECT --to ${health_port}
}
function remove {
instance=$1
instance_prefix="${instance}_prefix"
real_port="${!instance_prefix}${real}"
test_port="${!instance_prefix}${test}"
health_port="${!instance_prefix}${health}"
sudo iptables -t nat -D PREROUTING -m state --state NEW -p tcp --dport 8443 -j REDIRECT --to ${real_port}
sudo iptables -t nat -D PREROUTING -m state --state NEW -p tcp --dport 8444 -j REDIRECT --to ${test_port}
sudo iptables -t nat -D PREROUTING -m state --state NEW -p tcp --dport 8445 -j REDIRECT --to ${health_port}
}
# check which one was last reloaded -> i.e. via iptables list
status=$(iptables_status)
echo "Currently: "${status}
# if none exists default to blue (e.g. after boot)
# otherwise choose the opposite one reload it and swap the rules
if [[ ${status} == "none" ]]; then
echo "Initially routing to Blue"
sudo service haproxy-blue reload
add blue
elif [[ ${status} == "green" ]]; then
echo "Switching routing to Blue"
sudo service haproxy-blue reload
add blue
remove green
elif [[ ${status} == "blue" ]]; then
echo "Switching routing to Green"
sudo service haproxy-green reload
add green
remove blue
else
echo "[ALERT] unknown ipfilters state!"
sudo iptables -t nat -L -n -v
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.