Thursday, June 10, 2010

Setting up iperf as a daemon on CentOS

So I had a need to run iperf continuously on one of my CentOS servers today. I tested iperf in daemon mode and found that it wasn't very reliable. It crashed often, with the process needing to be killed and restarted. So I wrote up an init script and installed monit to monitor the port that iperf uses. Here is what you need to do:
yum -y install iperf monit
nano /etc/init.d/iperfd

Paste the following into the file:

#!/bin/bash
#
# iperfd iperf network bandwidth test
#
# chkconfig: 2345 80 30
# description: iperf network bandwidth test
# pidfile: /var/run/iperf.pid
# Source function library.

. /etc/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ ${NETWORKING} = "no" ] && exit 0

start() {
echo -n "Starting iperfd: "
/usr/bin/iperf -s -D >/dev/null 2>&1
touch /var/lock/subsys/iperfd
pidofproc iperf > /var/run/iperf.pid
return 1
}

stop() {
echo -n "Shutting down iperfd: "
killproc iperf
rm -f /var/lock/subsys/iperfd
rm -f /var/run/iperf.pid
return 1
}

case "$1" in
start)
start
;;
stop)
stop
;;
status)
status iperf
;;
restart)
stop
start
;;
*)
echo "Usage: iperfd {start|stop|restart}"
exit 1
;;
esac
exit $?

Setup Monit

nano /etc/monit.d/iperf

Paste the following into the file:

check process iperf with pidfile /var/run/iperf.pid
start program = "/etc/init.d/iperfd start"
stop program = "/etc/init.d/iperfd stop"
if failed host 127.0.0.1 port 5001 type TCP then restart
if 5 restarts within 5 cycles then timeout

chmod the monit files:

chmod 0700 /etc/monit.conf
chmod 0700 /etc/monit.d/iperf

Start up your services:

chkconfig monit on
chkconfig iperfd on
service iperfd start
service monit start