don't use HOSTNAME that is already set
[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 # using HOSTNAME won't work as this is already set in environment
42 while getopts "cf:i:m:n:h" flag; do
43     case $flag in
44         c) CONFIRM=true ;;
45         f) DISTRO=$OPTARG ;;
46         i) IMAGE=$OPTARG ;;
47         m) MEMORY=$OPTARG ;;
48         n) VM_HOSTNAME=$OPTARG ;;
49         ?|h) usage "" ;;
50     esac
51 done
52 # parse args
53 shift $((OPTIND-1))
54 [[ -z "$@" ]] && usage "no hostname provided"
55 container="$1" ; shift
56 [[ -n "$@" ]] && usage "extra arguments" "$@" "(container=$container)"
57
58 # sanity checks
59 [ -d "$BUILD" ] || usage "Could not find directory $BUILD"
60 [ -d /vservers/$container ] && usage "container $container already exists in /vservers"
61
62 # comopute all vars from args
63 [ -z "$DISTRO" ] && DISTRO="$DEFAULT_DISTRO"
64 [ -z "$VM_HOSTNAME" ] && VM_HOSTNAME="$container"
65 fqdn=$VM_HOSTNAME.$DOMAIN
66
67 # prepare initvm command
68 initvm="$BUILD/lbuild-initvm.sh"
69 initvm="$initvm -f $DISTRO"
70 initvm="$initvm -n $fqdn"
71 [ -n "$IMAGE" ] && initvm="$initvm -i $IMAGE"
72 [ -n "$MEMORY" ] && initvm="$initvm -m $MEMORY" 
73 initvm="$initvm $container"
74
75 if [ -n "$CONFIRM" ] ; then
76     echo -n "Run $initvm OK ? "
77     read answer ; case $answer in [nN]*) exit 1 ;; esac
78 fi
79
80 echo "Running $initvm"
81 echo "Storing output in $LOGS/$container.log"
82 $initvm >& $LOGS/$container.log
83