- add -l contortion so that backgrounded processes can re-open the log
[util-vserver.git] / scripts / vcached
1 #!/bin/bash
2 #
3 # vcached: VServer cache daemon
4 #
5 # Description: A daemon that periodically preallocates vservers and stores
6 # them in a cache.  Preallocated vservers from the cache may be then used to 
7 # instantiate real vservers. Requires that /var/run/vcached.pid does not
8 # exist on startup. Should start/stop/restart from /etc/init.d.
9 #
10 # Based on work by:
11
12 # Brent Chun - bnc@intel-research.net
13 # Tristan Koo - tristan.koo@intel-research.net
14 # William Wung - wungism@uclink.berkeley.edu
15 #
16 # Mark Huang <mlhuang@cs.princeton.edu>
17 # Copyright (c) 2004  The Trustees of Princeton University (Trustees).
18 #
19 # $Id: vcached,v 1.5 2004/10/12 21:27:15 mlhuang Exp $
20 #
21
22 # get configuration
23 . /etc/vcached.conf
24
25 # parse options
26 while getopts 'fdl:' OPT ; do
27     case "$OPT" in
28         f) foreground=1 ;;
29         d) debug=1 ;;
30         l) exec 1>>$OPTARG ; exec 2>>$OPTARG ;;
31     esac
32 done
33
34 # check if we are already running
35 if [ -f $pidfile ] ; then
36     echo "vcached(`cat $pidfile`) already running"
37     exit 1
38 fi
39
40 # daemonize
41 if [ $foreground -eq 0 ] ; then
42     nohup setsid nice -n $nice -- $0 $* -f -l $logfile >/dev/null 2>&1 </dev/null &
43     exit 0
44 fi
45
46 # record PID
47 trap "rm -f $pidfile ; exit 255" EXIT
48 trap "exec 1>>$logfile ; exec 2>>$logfile" HUP
49 echo $$ > $pidfile
50
51 : ${UTIL_VSERVER_VARS:=$(dirname $0)/util-vserver-vars}
52 test -e "$UTIL_VSERVER_VARS" || {
53     echo "Can not find util-vserver installation; aborting..."
54     exit 1
55 }
56 . "$UTIL_VSERVER_VARS"
57
58 # take out the trash
59 chattr -R -i "$VROOTDIR/.vtmp"
60 rm -rf "$VROOTDIR/.vtmp"
61
62 mkdir -p "$VROOTDIR/.vcache"
63 mkdir -p "$VROOTDIR/.vtmp"
64
65 # loop forever
66 while : ; do
67     [ $debug -ne 0 ] && echo "$(date) Checking the cache"
68     for i in $(seq 0 $(($slots - 1))) ; do
69         if [ ! -d "$VROOTDIR/.vcache/v$i" ] ; then
70             echo "$(date) Caching v$i"
71             # build image in .vtmp
72             TMP=$(mktemp -d "$VROOTDIR/.vtmp/v$i.XXXXXX")
73             "$PKGLIBDIR/vbuild" "$VROOTDIR/vserver-reference" "$TMP"
74             RETVAL=$?
75             # move it to .vcache when complete
76             if [ $RETVAL -eq 0 ] ; then
77                 mv "$TMP" "$VROOTDIR/.vcache/v$i"
78                 echo "$(date) v$i ready"
79             else
80                 echo "$(date) Error $RETVAL building v$i"
81                 chattr -R -i "$TMP"
82                 rm -rf "$TMP"
83             fi
84         fi
85     done
86     [ $debug -ne 0 ] && echo "$(date) Sleeping for $period seconds"
87     sleep $period
88 done