Skip to content

Instantly share code, notes, and snippets.

@bndw
Created September 29, 2016 19:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bndw/e3094e42843809f1f1377a2aa1db3ab9 to your computer and use it in GitHub Desktop.
Save bndw/e3094e42843809f1f1377a2aa1db3ab9 to your computer and use it in GitHub Desktop.
#!/bin/bash
#
# Reloads HAProxy and kills the old instances kept alive by open connections.
#
# Old HAProxy instances will only be killed if they're:
# * bound to ports in CHOPPABLE_PORTS
# * not the active HAProxy process, as defined by PID_FILE
CONF=/etc/haproxy/haproxy.cfg
PID_FILE=/run/haproxy.pid
# Ports HAProxy is listening on
LISTEN_PORTS=80,443,6001
# Ports we're willing to drop connections on
CHOPPABLE_PORTS=6001
if [[ "$EUID" -ne 0 ]] ; then
echo Must run as root
exit 1
fi
validate_config() {
msg=$(haproxy -c -f "${CONF}" 2>&1)
code=$?
if [[ "${code}" -ne 0 ]] ; then
echo Invalid config file: "${CONF}"
echo "${msg}"
exit 2
fi
}
reload() {
systemctl reload haproxy
}
kill_dangling_haproxy_processes() {
listeners=($(lsof -i tcp:${LISTEN_PORTS} | tail -n +2 | grep -i listen | awk '{ print $2 }'))
disposable=($(lsof -i tcp:${CHOPPABLE_PORTS} | tail -n +2 | grep -i established | awk '{ print $2 }'))
for pid in "${disposable[@]}" ; do
if [[ "${pid}" -eq "${active_worker}" ]] ; then
echo "Established websocket connection being served by new worker ${pid}, skipping."
fi
for listener in "${listeners[@]}" ; do
if [[ "${pid}" -eq "${listener}" ]] ; then
echo "Established websocket connection being served by a worker ${pid} bound to listening ports, skipping."
fi
done
echo "Killing worker ${pid}" && kill ${pid}
if [[ $? -ne 0 ]] ; then
echo "Failed to kill ${pid} with code $?"
exit 3
fi
done
}
validate_config
reload
kill_dangling_haproxy_processes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment