Restarting Apache with Python

It doesn't happen a lot but when it does it is frustrating. Since the server that runs this site is modest in every means I sometimes will check out how things are going and find out that the Apache2 web server has stopped running on the server. The last time this happened I did a quick search to see what others were doing to manage the problem. There were a few packages that will monitor the server for you and then restart it if needed but every one of them took a lot more work to manage and install than I really wanted to do. So I wrote a quick Python script that combined with cron do the job very nicely.

#!/usr/bin/env python

from os import system, path

pidFile = '/var/run/apache2.pid'
startCmd = 'apache2 -k start'

if not path.exists(pidFile):
    system(startCmd)

The basic idea is that most *nix services use a pid file to store the ID number of the process that was assigned to the service when the service was started. If the service is running then there will be a pid file for that service and no pid file if the service is not running.

To start out, test to see whether the pid file exists. It is located at /var/run/apache2.pid on my server. Your setup may vary so check your setup before proceeding. I also created a symlink to /usr/bin for Apache at /usr/bin/apache2 -> /etc/init.d/apache2 which allows me to type just 'Apache2' at the prompt instead of the entire path to Apache. If the pid file does not exist that means Apache isn't running so go ahead and send a start command to the server via 'apache2 –k start'

I saved this code as a file in my home directory and created a cron job to run the file once each minute.

Comments