14.17. Running MRTG As a Daemon

You know that running MRTG from cron consumes more system resources because it loads and parses the configuration file or files every time it starts. So, you want to run it as a daemon. How do you do this?

It takes a number of steps, so roll up your sleeves and follow along:

Create a user and group just for running MRTG:

	# groupadd mrtg
	# useradd -d /dev/null -g mrtg -s /bin/false mrtg

Hunt down and change all files that the mrtg user must have write permissions for, and change them:

	# chown -R mrtg:mrtg /var/www/mrtg
	# chown -R mrtg:mrtg /var/log/mrtg/

Add these lines to the Global section of mrtg.cfg:

	RunAsDaemon: Yes
	Interval:    5

Delete all existing cron jobs, or just move them out of the way in case you want them back:

	# mv /etc/cron.d/mrtg ../mrtg

Create a lockfile, and start MRTG from the command line:

	# mkdir /var/lock/mrtg/
	# chown -R mrtg:mrtg /var/lock/mrtg/
	# env LANG=C mrtg --daemon --user=mrtg --group=mrtg /etc/mrtg.cfg
	Daemonizing MRTG ...

If you have more than one configuration file, line 'em up:

	# env LANG=C mrtg --daemon --user=mrtg --group=mrtg /etc/mrtg.cfg /etc/mrtg-uberpc.
	cfg

Check with the ps command:

	$ ps ax|grep mrtg
	26324 ? Ss 0:00 /usr/bin/perl -w /usr/bin/mrtg --daemon --user=mrtg --group=mrtg /
	etc/mrtg.cfg

And that shows we are successful!

To start it automatically at boot, you'll need a file in /etc/init.d, and startup links on the runlevels you want to use. An init file can be as simple as this:

	#!/bin/sh
	## /etc/init.d/mrtg
	# chkconfig 2345 90 30
	#
	mkdir /var/lock/mrtg/
	chown -R mrtg:mrtg /var/lock/mrtg/
	# this must be one unbroken line
	env LANG=C mrtg --daemon --user=mrtg --group=mrtg /etc/mrtg.cfg \
	/etc/mrtg-uberpc.cfg

Make it executable:

	# chmod +x /etc/init.d/mrtg

Then, create your startup links on Debian with update-rc.d:

	# update-rc.d mrtg start 90 2 3 4 5 . stop 30 0 1 6

Fedora uses chkconfig:

	# chkconfig --add mrtg

You really need a better init file than the example. Debian users can use /etc/init.d/ skeleton as a model for creating new startup files.

This is a basic startup script that should work anywhere:

	#! /bin/sh
	## /etc/init.d/foo
	#
	# most apps need a lockfile
	touch /var/lock/foo

	# start 'er up
	  case "$1" in
	    start)
	      echo "Starting script foo "
	      echo "optional other things here"
	      ;;
	    stop)
	      echo "Stopping script foo now"
	      echo "optional other things here"
	      ;;
	     *)
	   echo "Usage: /etc/init.d/foo {start|stop}"
	   exit 1
	   ;;
	esac
	exit 0