536289e505ee033b90b5ce362f9a4712fbc3fc77
[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=f21
20
21 CONFIRM=
22 function usage () {
23   message="$@" 
24   echo "usage : $COMMAND [-c] [-f distro] [-i image] [ -m memory ] [ -n hostname ] [-s] 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 2048"
30   echo " -n : specify hostname if different from container"
31   echo " -s : do not start VM"
32   echo " container : used for /vservers/foo as well as the lxc/libvirt name"
33   echo "examples"
34   echo "  create-vm.sh sandbox"
35   echo "    Builds a brand new $DEFAULT_DISTRO 64bits VM named sandbox with hostname sandbox.pl.sophia.inria.fr"
36   echo "  create-vm.sh -i /vservers/migrating/testmaster -n testmaster testmaster.f14"
37   echo "    Create a container named testmaster.f14 from the specified image with hostname testmaster.pl.sophia.inria.fr"
38   [ -n "$message" ] && echo $message
39   exit 1
40 }
41
42 # using HOSTNAME won't work as this is already set in environment
43 while getopts "cf:i:m:n:sh" flag; do
44     case $flag in
45         c) CONFIRM=true ;;
46         f) DISTRO=$OPTARG ;;
47         i) IMAGE=$OPTARG ;;
48         m) MEMORY=$OPTARG ;;
49         n) VM_HOSTNAME=$OPTARG ;;
50         s) DO_NOT_START_VM=true ;;
51         ?|h) usage "" ;;
52     esac
53 done
54 # parse args
55 shift $((OPTIND-1))
56 [[ -z "$@" ]] && usage "no hostname provided"
57 container="$1" ; shift
58 [[ -n "$@" ]] && usage "extra arguments" "$@" "(container=$container)"
59
60 # sanity checks
61 [ -d "$BUILD" ] || usage "Could not find directory $BUILD"
62 [ -d /vservers/$container ] && usage "container $container already exists in /vservers"
63
64 # compute all vars from args
65 [ -z "$DISTRO" ] && DISTRO="$DEFAULT_DISTRO"
66 [ -z "$VM_HOSTNAME" ] && VM_HOSTNAME="$container"
67 fqdn=$VM_HOSTNAME.$DOMAIN
68
69 # prepare initvm command
70 initvm="$BUILD/lbuild-initvm.sh"
71 [ -z "$IMAGE" ] && initvm="$initvm -f $DISTRO" || initvm="$initvm -i $IMAGE"
72 initvm="$initvm -n $fqdn"
73 [ -n "$DO_NOT_START_VM" ] && initvm="$initvm -s"
74 [ -n "$MEMORY" ] && initvm="$initvm -m $MEMORY" 
75 initvm="$initvm $container"
76
77 if [ -n "$CONFIRM" ] ; then
78     echo -n "Run $initvm OK ? "
79     read answer ; case $answer in [nN]*) exit 1 ;; esac
80 fi
81
82 echo "Running $initvm"
83 echo "Storing output in $LOGS/$container.log"
84 $initvm >& $LOGS/$container.log
85