Skip to content

Instantly share code, notes, and snippets.

@tomazzaman
Created September 20, 2016 11:43
Show Gist options
  • Save tomazzaman/ed94c45856a6a6c81d539ac0ff054132 to your computer and use it in GitHub Desktop.
Save tomazzaman/ed94c45856a6a6c81d539ac0ff054132 to your computer and use it in GitHub Desktop.
PostgreSQL health check through xinetd (with repmgr)
# description: An xinetd service to show PSQL status
# put this file into /etc/xinetd.d
service postgrescheck
{
type = UNLISTED
flags = REUSE
wait = no
disable = no
socket_type = stream
protocol = tcp
user = postgres
server = /usr/local/bin/postgresqlcheck
port = 5433
only_from = 0.0.0.0/0
per_source = UNLIMITED
log_type = SYSLOG daemon debug
}
#!/bin/bash
# Put this file into /usr/local/bin and
# chmod +x it
IP=$(hostname -i)
FIELDS="conninfo, type, active"
SQL="SELECT ${FIELDS} FROM repmgr_test.repl_nodes WHERE conninfo LIKE '%${IP}%';"
return_fail() {
echo -e "HTTP/1.1 503 Service Unavailable\r\n"
echo -e "Content-Type: text/html\r\n"
echo -e "Content-Length: 40\r\n"
echo -e "Connection: close\r\n"
echo -e "\r\n"
echo -e "<html><body>This is a slave, shouldn't be accessible.</body></html>\r\n"
echo -e "\r\n"
exit 1
}
return_ok() {
echo -en "HTTP/1.1 200 OK\r\n"
echo -en "Content-Type: text/plain\r\n"
echo -en "Content-Length: 29\r\n"
# echo -en "Connection: close\r\n"
echo -en "\r\n"
echo -en "PostgreSQL master is running.\r\n"
echo -en "\r\n"
exit 0
}
# This part needs to be here and it's basicall what the "request"
# part of the http check looks like. We just wait for a blank (or really short)
# line which a newline is and only then proceeding with the
# "response" part, which is in the next while loop
while read line; do
if [ $(echo $line | wc -c) -lt "3" ]; then
break
fi
done
while read LINE; do
# Uncomment the following line for debugging
# echo "${LINE}"
TYPE=$(echo "${LINE}" | awk -F '|' '{print $2}' | tr -d '[[:space:]]')
ACTIVE=$(echo "${LINE}" | awk -F '|' '{print $3}' | tr -d '[[:space:]]')
if [ "${TYPE}" == "master" ] && [ "${ACTIVE}" == "t" ] ; then
return_ok
fi
done < <(psql -U repmgr -d repmgr -c "${SQL}" | grep "host")
return_fail
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment