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