Even though we have already presented quite a few scripts over the last couple of weeks to perform automatic failover at Hetzner using Heartbeat, we also want to provide failover for setups where we don’t use any failover addresses. For these types of setups, we have written a shell script, called HostHenker.
HostHenker is a small shell script, which uses nc(1) to determine whether a daemon is listening on a given host. Based on whether a daemon is running, it adds an entry to /etc/hosts for this host or a fallback host. Invocation of this utility is simple:
hosthenker mysql.example.com 3306 10.0.0.7 10.0.0.8
In this setup, the script tries to connect to 10.0.0.7:3306 and writes an entry for mysql.example.com to /etc/hosts. The actual command invoked by this script is nc -zw 15. The -z flag enables zero-I/O-mode, effectively closing the connection as soon as it has been established, while -w 15 sets a 15-second timeout, which is often good enough.
Right before installing the new /etc/hosts file, HostHenker checks whether the new file is different from the original one. If this is the case, it writes a string to stderr, which can be useful when configuring this script to run as a cronjob.