5 # Dobrica Pavlinusic <dpavlin@rot13.org> 2010-03-15
7 # this script can be used to start/stop Linux containers
8 # using clever inotify hack to monitor halt/reboot from
9 # Tony Risinger posted to lxc-users mailing list
11 # http://www.mail-archive.com/lxc-users@lists.sourceforge.net/msg00074.html
14 which inotifywait >/dev/null || apt-get install inotify-tools
20 if [ ! -e /var/lib/lxc/$name/config ] ; then
29 grep lxc.rootfs "/var/lib/lxc/$1/config" | cut -d= -f2 | sed 's/^ *//'
34 lxc-ls -1 | sort -u | xargs -i lxc-info -n {} | sed "s/'//g" | while read name is status ; do
36 test -s /var/lib/lxc/$name/on_boot && on_boot="on_boot"
37 echo "$name $status $on_boot $(lxc_rootfs $name)"
42 cleanup_init_scripts() {
43 rootfs=$(lxc_rootfs $1)
46 $rootfs/etc/rc?.d/*umountfs \
47 $rootfs/etc/rc?.d/*umountroot \
48 $rootfs/etc/rc?.d/*hwclock* \
49 2>/dev/null | xargs -i rm -v {}
54 rootfs=$(lxc_rootfs $1)
58 # let container respond to kill -SIGPWR
59 inittab=$rootfs/etc/inittab
60 if ! grep "$add" ${inittab} >/dev/null ; then
61 grep -v "$remove" ${inittab} > ${inittab}.new
62 echo $add >> ${inittab}.new
63 mv ${inittab}.new ${inittab}
64 echo "$inittab modified with $add"
73 init_pid=`lxc-ps -C init -o pid | grep "^$name" | cut -d" " -f2-`
74 if [ -z "$init_pid" ] ; then
78 echo "$name kill $sig $init_pid"
79 /bin/kill $sig $init_pid
83 lxc_kill $name -SIGPWR
84 lxc-wait -n $name -s STOPPED
85 # rm -f /var/lib/lxc/${name}/on_boot
92 if ! lxc-info -n $name | grep RUNNING ; then
94 lxc-start -n $name -o /tmp/${name}.log -d
95 lxc-wait -n $name -s RUNNING
97 echo $name > /var/lib/lxc/${name}/on_boot
103 rootfs=$(lxc_rootfs $1)
106 vps_utmp=${rootfs}/var/run/utmp
107 tasks=`wc -l < /cgroup/${name}/tasks`
108 test -z "$tasks" && exit 1
109 if [ "$tasks" -eq 1 ]; then
111 runlevel="$(runlevel ${vps_utmp})"
112 echo `date +%Y-%m-%dT%H:%M:%S` "$name runlevel $runlevel"
116 # nothing for new boot state
120 lxc-stop -n "${name}"
121 lxc-wait -n ${name} -s STOPPED
127 lxc-wait -n ${name} -s STOPPED
128 lxc-start -d -n ${name} -o /tmp/${name}.log
131 # make sure vps is still running
132 state="$(lxc-info -n "${name}" | sed -e 's/.* is //')"
133 [ "$state" = "RUNNING" ] || break
137 echo "# $name $tasks tasks"
140 # time of 5 minutes on it JUST IN CASE...
141 inotifywait -qqt 300 ${vps_utmp}
144 echo "${name} exited"
159 cleanup_init_scripts $1
160 setup_inittab $1 ::power "p0::powerfail:/sbin/init 0"
161 setup_inittab $1 ::ctrlaltdel "p6::ctrlaltdel:/sbin/init 6"
163 ( nohup $0 watchdog $1 >> /tmp/$1.log 2>/dev/null ) &
169 reload|force-reload|restart|reboot)
176 echo "Usage: $0 {start|stop|restart|status}" >&2
187 test "$command" = "status" && lxc_status && exit
189 if [ -z "$1" ] ; then
190 ls /var/lib/lxc/*/on_boot | while read path ; do
191 name=`echo $path | cut -d/ -f5`
192 command_on_lxc $command $name
195 while [ ! -z "$1" ] ; do
196 command_on_lxc $command $1