Charles Hooper

Thoughts and projects from a site reliability engineer

Controlling Django Apps With an Init Script

If you’re reading this, you probably already know that an init script is a specific style of script that allows you to control daemon processes. In particular, they are used to start processes at boot and terminate them at shutdown. What follows is an example script I use to control one of my Django FastCGI projects. This particular example was written for Ubuntu and Debian but could probably be modified for RedHat/CentOS or other distros.

Please refer to your Distro’s documentation on how to install and activate init scripts (hint: See /etc/init.d/ and the man page for update-rc.d if on Debian or Ubuntu.)

django-fcgi-init.shlink
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#!/bin/sh

PATH=/sbin:/bin:/usr/sbin:/usr/bin

FCGIHOST="127.0.0.1"
FCGIPORT="5000"
RUNAS="projectuser:projectgroup"
UMASK="200"
DAEMON="/path/to/django/manage.py"
NAME="MyProject"
DESC="My Django Project"
RUNDIR=/var/run/$NAME
PIDFILE=/var/run/$NAME/$NAME.pid
ENV="env -i LANG=C PATH=/usr/local/bin:/usr/bin:/bin"
SSD="/sbin/start-stop-daemon"

DAEMON_OPTS="runfcgi host=$FCGIHOST port=$FCGIPORT pidfile=$PIDFILE
daemonize=true"

test -x $DAEMON || exit 0

set -e

. /lib/lsb/init-functions

# Set up /var/run directory to write out pidfile
mkdir -p "$RUNDIR"
chown "$RUNAS" "$RUNDIR"
chmod 775 "$RUNDIR"

case "$1" in
 start)
 log_daemon_msg "Starting $DESC" $NAME
 if ! start-stop-daemon --start --quiet --oknodo \
 --pidfile $PIDFILE --umask "$UMASK" --chuid "$RUNAS" \
 --exec $DAEMON -- $DAEMON_OPTS
 then
 log_end_msg 1
 else
 chmod 400 $PIDFILE
 log_end_msg 0
 fi
 ;;
 stop)
 log_daemon_msg "Stopping $DESC" $NAME
 if [ -f $PIDFILE ]; then
 kill `cat -- $PIDFILE`
 rm -f -- $PIDFILE
 log_end_msg 0
 fi
 ;;
 restart|force-reload)
 $0 stop
 $0 start
 ;;
 status)
 status_of_proc -p "$PIDFILE" "$DAEMON" "$NAME" && exit 0 || exit $?
 ;;
 *)
 echo "Usage: $0 {start|stop|restart|force-reload|status}" >&2
 exit 1
 ;;
esac

exit 0

Comments