- vbuild was hanging because of a corrupt RPM database. Eventually it
[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.2 2004/08/19 22:09:20 mlh-pl_kernel Exp $
20 #
21
22 # number of images to keep cached
23 slots=32
24
25 # fill the cache periodically
26 period=$((60 * 15))
27
28 # nice adjustment
29 nice=10
30
31 # PID file
32 pidfile=/var/run/vcached.pid
33
34 # log file
35 logfile=/var/log/vcached.log
36
37 # run in foreground
38 foreground=0
39
40 # debug
41 debug=0
42
43 # parse options
44 while getopts 'fd' OPT ; do
45     case "$OPT" in
46         f) foreground=1 ;;
47         d) debug=1 ;;
48     esac
49 done
50
51 # check if we are already running
52 [ -f $pidfile ] && exit 1
53
54 # daemonize
55 if [ $foreground -eq 0 ] ; then
56     nohup nice -n $nice -- $0 $* -f >>$logfile 2>&1 &
57     exit 0
58 fi
59
60 # record PID
61 trap "rm -f $pidfile ; exit 255" EXIT
62 echo $$ > $pidfile
63
64 : ${UTIL_VSERVER_VARS:=$(dirname $0)/util-vserver-vars}
65 test -e "$UTIL_VSERVER_VARS" || {
66     echo "Can not find util-vserver installation; aborting..."
67     exit 1
68 }
69 . "$UTIL_VSERVER_VARS"
70
71 # take out the trash
72 chattr -R -i "$VROOTDIR/.vtmp"
73 rm -rf "$VROOTDIR/.vtmp"
74
75 mkdir -p "$VROOTDIR/.vcache"
76 mkdir -p "$VROOTDIR/.vtmp"
77
78 # loop forever
79 while : ; do
80     [ $debug -ne 0 ] && echo "$(date) Checking the cache"
81     for i in $(seq 0 $(($slots - 1))) ; do
82         if [ ! -d "$VROOTDIR/.vcache/v$i" ] ; then
83             echo "$(date) Caching v$i"
84             # build image in .vtmp
85             TMP=$(mktemp -d "$VROOTDIR/.vtmp/v$i.XXXXXX")
86             "$PKGLIBDIR/vbuild" "$VROOTDIR/vserver-reference" "$TMP"
87             RETVAL=$?
88             # move it to .vcache when complete
89             if [ $RETVAL -eq 0 ] ; then
90                 mv "$TMP" "$VROOTDIR/.vcache/v$i"
91                 echo "$(date) v$i ready"
92             else
93                 echo "$(date) Error $RETVAL building v$i"
94                 rm -rf "$TMP"
95             fi
96         fi
97     done
98     [ $debug -ne 0 ] && echo "$(date) Sleeping for $period seconds"
99     sleep $period
100 done