bugfix
[infrastructure.git] / scripts / create-vm.sh
1 #!/bin/bash
2
3 COMMAND=$(basename $0)
4 DIRNAME=$(dirname $0)
5
6 BUILD="${HOME}/git-build"
7
8 echo "Updating $BUILD"
9 cd $BUILD
10 git pull
11 cd -
12
13 LOGS=$HOME/machines
14
15 [ -d $LOGS ] || { echo "Creating logs dir $LOGS" ; mkdir -p $LOGS; } 
16
17 DOMAIN=pl.sophia.inria.fr
18
19 DEFAULT_DISTRO=f20
20
21 CONFIRM=
22 function usage () {
23   message="$@" 
24   echo "usage : $COMMAND [-c] [-f distro] [-i image] [ -m memory ] [ -n hostname ] container"
25   echo " -c : confirm, will show the command and prompt for confirmation "
26   echo " -f : set distro, default is $DEFAULT_DISTRO"
27   echo " -i : if specified, image is rsynced into /vservers"
28   echo "      warning: we cannot use an image already in /vservers..."
29   echo " -m : memory size in Mb - default is 512"
30   echo " -n : specify hostname if different from container"
31   echo " container : used for /vservers/foo as well as the lxc/libvirt name"
32   echo "examples"
33   echo "  create-vm.sh sandbox"
34   echo "    Builds a brand new $DEFAULT_DISTRO 64bits VM named sandbox with hostname sandbox.pl.sophia.inria.fr"
35   echo "  create-vm.sh -i /vservers/migrating/testmaster -n testmaster testmaster.f14"
36   echo "    Create a container named testmaster.f14 from the specified image with hostname testmaster.pl.sophia.inria.fr"
37   [ -n "$message" ] && echo $message
38   exit 1
39 }
40
41 while getopts "cf:i:m:n:h" flag; do
42     case $flag in
43         c) CONFIRM=true ;;
44         f) DISTRO=$OPTARG ;;
45         i) IMAGE=$OPTARG ;;
46         m) MEMORY=$OPTARG ;;
47         n) HOSTNAME=$OPTARG ;;
48         ?|h) usage "" ;;
49     esac
50 done
51 # parse args
52 shift $((OPTIND-1))
53 [[ -z "$@" ]] && usage "no hostname provided"
54 container="$1" ; shift
55 [[ -n "$@" ]] && usage "extra arguments" "$@" "(container=$container)"
56
57 # sanity checks
58 [ -d "$BUILD" ] || usage "Could not find directory $BUILD"
59 [ -d /vservers/$container ] && usage "container $container already exists in /vservers"
60
61 # comopute all vars from args
62 [ -z "$DISTRO" ] && DISTRO="$DEFAULT_DISTRO"
63 [ -z "$HOSTNAME" ] && HOSTNAME="$container"
64 fqdn=$HOSTNAME.$DOMAIN
65
66 # prepare initvm command
67 initvm="$BUILD/lbuild-initvm.sh"
68 initvm="$initvm -f $DISTRO"
69 initvm="$initvm -n $fqdn"
70 [ -n "$IMAGE" ] && initvm="$initvm -i $IMAGE"
71 [ -n "$MEMORY" ] && initvm="$initvm -m $MEMORY" 
72 initvm="$initvm $container"
73
74 if [ -n "$CONFIRM" ] ; then
75     echo -n "Run $initvm OK ? "
76     read answer ; case $answer in [nN]*) exit 1 ;; esac
77 fi
78
79 echo "Running $initvm"
80 echo "Storing output in $LOGS/$container.log"
81 $initvm >& $LOGS/$container.log
82