Keeping Your Django Project Alive

August 17, 2010 in django

The Bash Script

I must admit, I'm relatively new to bash scripting. However, the more I explore the powerful functionality you can create with nothing more than a tiny script running on a schedule, the more I find myself looking for excuses to do so. I'll start by creating a file named djangostart.sh which I'll place in the root directory of my web app which looks like this:

#!/bin/bash

USER="user"

# the name of your app directory
DJANGO_APP="django"

# the name of your memcache directory
MEM_INSTANCE="pixeldonor_memcached"

# an identifier for the apache process running on the server
PROC1="/home/$USER/webapps/$DJANGO_APP/apache2/bin/httpd"

# and identifier for the memcache process running on the server
PROC2="/home/$USER/webapps/$MEM_INSTANCE/memcached"

# the minimum number of apache workers that should be running + 1
INSTANCES1=3

# the minimum number of memcache instances that should be running + 1
INSTANCES2=2

# the process ID of our memcache, assuming its running
MEMPID=$(pgrep -u $USER -f $PROC2)

# how many apache processes are running
COUNT1=$(ps -u $USER -o command | grep -c $PROC1)

# how many memcache processes are running
COUNT2=$(ps -u $USER -o command | grep -c $PROC2)

# the command to restart memcached
STARTMEM="/usr/local/bin/memcached -d -m 64 -s /home/$USER/webapps/$MEM_INSTANCE/memcached.sock"

# if either count is less than the number of required instances:
# kill apache, kill memcached, start memcached, start apache
if [ "$COUNT1" -lt "$INSTANCES1" -o "$COUNT2" -lt "$INSTANCES2" ]; then
	/home/$USER/webapps/$DJANGO_APP/apache2/bin/stop
	kill $MEMPID
	$STARTMEM
	sleep 5
	/home/$USER/webapps/$DJANGO_APP/apache2/bin/start
fi

You'll notice the COUNT variables are offset by 1, this is because (at least from what I've noticed) the actual grep process will show up and match when you're filtering through the active processes. The rest of the code is explained in the comments.

Scheduling Restarts

Once again we turn to the help of cron to run our bash script regularly. In an SSH session, type crontab -e and use the following for your cron job:

5,25,45 * * * * /home/user/webapps/django/djangostart.sh > /dev/null 2>&1

This cron job will run our bash script every 20 minutes and ensure our site and memcached are up and running.

Tagged in
apache  cron  django  python 

Comments are closed.

Comments have been closed for this post.