a4a00d0552479a8071b679e962ad9edb8a0244cf
[tests.git] / system / template-qemu / qemu-kill-node
1 #!/bin/sh
2 # $Id$
3 COMMAND=$(basename $0)
4 cd $(dirname $0)
5 cd ..
6
7 # somehow qemu-system-x86_64 show up in pgrep as qemu-system-x86
8 COMMANDS_TO_KILL="qemu qemu-system-x86_64 qemu-system-x86"
9
10 function usage () {
11     echo "Usage: $COMMAND -l"
12     echo "  lists current qemu processes"
13     echo "usage: $COMMAND hostname"
14     echo "  kill qemu instance for that node"
15     echo "usage: $COMMAND"
16     echo "  kill all instances of [$COMMANDS_TO_KILL]"
17     exit 1
18 }
19
20 function list_pids () {
21     hostnames="$@"
22     if [[ -n "$hostnames" ]] ; then
23         for hostname in $hostnames; do
24             nodedir=qemu-$hostname
25             cat $nodedir/qemu.pid 2> /dev/null
26         done
27     else
28         for command in $COMMANDS_TO_KILL; do
29             pgrep -x $command
30         done
31     fi
32 }
33
34 function kill_from_file () {
35     file=$1; shift
36     if [ -f $file ] ; then
37         pid=$(cat $file)
38         echo Killing $pid
39         kill $pid
40         mv $file $file.killed
41     else
42         echo "Could not find file $file - that qemu was killed already"
43     fi
44 }    
45
46 function kill_pids () {
47     hostnames="$@"
48     if [[ -n "$hostnames" ]] ; then
49         for hostname in $hostnames; do
50             nodedir=qemu-$hostname
51             kill_from_file $nodedir/qemu.pid
52         done
53     else
54         echo "Killing all processes mathing $COMMANDS_TO_KILL"
55         for command in $COMMANDS_TO_KILL ; do
56             pkill -x $command
57         done
58     fi
59 }
60
61 function show_pids () {
62     pids=$(list_pids "$@")
63     if [ -n "$pids" ] ; then
64         ps $pids | grep -v $COMMAND || echo Nothing to show
65     else
66         echo Nothing to show
67     fi
68 }
69
70 function main () { 
71     while getopts "lk" opt; do
72         case $opt in
73             l) OPT_LIST=true ;;
74             k) OPT_GREP=true ;;
75             *) usage ;;
76         esac
77     done
78     shift $(($OPTIND -1))
79
80     # listing
81     if [ -n "$OPT_LIST" ] ; then
82         show_pids "$@"
83         exit 0
84     fi
85
86     kill_pids "$@"
87 }
88
89 main "$@"