Monday 23 March 2009

How to run an application a daemon? Example with nsca Nagios utility

Recently I needed to make a server application run as an Unix daemon and be able to start, stop and restart it on demand. The application I’m talking about didn’t have any startup/shutdown utilities (nsca utility to send passive check results to Nagios). It runs as a script, without even detaching from the console ( unless you use the & at the end of the command line, let's say #nsca -c nsca.cfg & ).
I also did it some time ago, to make another utility work as a daemon, but today I want to share the info.
I’ll have to write a utility application that would start the process, store it’s PID in some file and somehow “daemonize” the forked process.

Let’s assume that the application we want to run is /usr/local/nagios/nsca

First, we need to create a script in /etc/init.d/ Let us name the file /etc/init.d/nsca

The file contents would look something like this:

#!/bin/bash
#
# /etc/rc.d/init.d/nsca
#
# Control to start/stop nsca utility as a daemon
# chkconfig: 345 99 01
# description: NSCA passive alerts writer for Nagios
#
# Author: Edwin Salvador (edwin.salvador@gmail.com)
#
# Changelog:
# 2009-03-23
# - First version of the script
#
# processname: nsca
# Source function library.
. /etc/init.d/functions

test -x /usr/local/nagios/nsca || exit 0

RETVAL=0

prog="NSCA passive alerts writer for Nagios"

start() {
echo -n $"Starting $prog: "
daemon /usr/local/nagios/nsca -c /usr/local/nagios/nsca.cfg
RETVAL=$?
[ $RETVAL -eq 0 ] && touch /var/lock/subsys/nsca
echo
}

stop() {
echo -n $"Stopping $prog: "
killproc /usr/local/nagios/nsca
RETVAL=$?
[ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/nsca
echo
}

#
# See how we were called.
#
case "$1" in
start)
start
;;
stop)
stop
;;
reload|restart)
stop
start
RETVAL=$?
;;
condrestart)
if [ -f /var/lock/subsys/nsca ]; then
stop
start
fi
;;
status)
status /usr/local/nagios/nsca
RETVAL=$?
;;
*)
echo $"Usage: $0 {condrestart|start|stop|restart|reload|status}"
exit 1
esac

exit $RETVAL


This is a pretty standard service start/stop/restart file. This small script will take care of controlling the PID and work as any other standard service, you don't need to remove any PID file manually, nor event to kill the process.

It can also be easyly modified to match any other program / application / script under Linux you want to daemonize !!.

Remember to assign user and group "root", and chmod 755
Use a different and unique name to each new startup script you create.

You're all set. Just use it as any usual service you run:

START:
#service start nsca
STOP:
#service stop nsca
RESTART:
#service restart nsca

If you need it to startup automatically on system boot-up:

#chkconfig nsca on

Enjoy it !

No comments:

Post a Comment