7311ab185534a9b3367a162df1afbb502320ed2a
[matthijs/servers/drsnuggles.git] / usr / local / bin / vserver-create
1 #!/bin/sh
2
3 # The dir containing vserver configuration
4 VSERVERS_CONF=/etc/vservers
5 # The vserver to use as a template
6 TEMPLATE=template
7 # A file containing files (or masks) to not copy from the template vserver.
8 EXCLUDE_FILE="$VSERVERS_CONF/clone-exclude"
9 # The ip range to use for creating a new vserver. A number between 2 and 253
10 # will be appended to this, until an address is found that is not used by
11 # another vserver..
12 IP_RANGE=10.42.0.
13 # The interface on which to create the vserver
14 INTERFACE=dummy0
15 # The netmask for the address
16 NETMASK=24
17
18 function usage()
19 {
20         echo "Usage: $0 name"
21         echo "Creates a new vserver with the specified name, which is a clone"
22         echo "from the vserver \`\`$TEMPLATE'' with some post-processing done."
23 }
24
25 function find_ip()
26 {
27         IP_FILES="$VSERVERS_CONF/*/interfaces/*/ip"
28         for i in {2..53}; do
29                 IP=${IP_RANGE}$i
30                 if ! grep ^$IP$ $IP_FILES &>/dev/null; then
31                         return 0
32                 fi
33         done
34         return 1
35 }
36
37 # Check arguments
38 if [ ! "$#" -eq 1 ]; then
39         usage
40         exit 1
41 fi
42
43 NAME=$1
44
45 if ! echo $NAME | grep "^[a-zA-Z0-9-]*$" &>/dev/null; then
46         echo "Name can only contain alphanumerics and dashes"
47         exit 1
48 fi
49
50 HOST="$NAME/`hostname --fqdn`"
51
52 # Set the IP var
53 if ! find_ip; then
54         echo "No available ip address found, aborting"
55         exit 1
56 fi;
57
58 echo "Creating vserver $NAME with address $IP..."
59 sudo vserver $NAME build -m clone --hostname $HOST --interface $INTERFACE:$IP/$NETMASK -- --source $TEMPLATE --exclude-from $EXCLUDE_FILE
60
61 echo "Vserver created, configuring..."
62 sudo vserver $NAME start
63 # Regen ssh keys
64 sudo vserver $NAME exec dpkg-reconfigure openssh-server
65 # Setup git - Add a branch for this vserver
66 sudo vserver $NAME exec git branch $NAME origin/$TEMPLATE
67 sudo vserver $NAME exec git checkout $NAME
68 # Remove the template branch, to prevent pushing it back later on 
69 sudo vserver $NAME exec git branch -d $TEMPLATE
70 # Push our new branch upstream so it can be pushed with "git push" afterwards.
71 sudo vserver $NAME exec git push origin $NAME:$NAME
72 # Enable vhashify/vunify
73 sudo mkdir $VSERVER_CONF/$NAME/apps/vunify
74 sudo touch $VSERVER_CONF/$NAME/apps/vunify/dummy # For git
75
76 # Remove trailing slashes from the confdir. git only works when we're using
77 # relative paths and the cwd is / for some reason...
78 CONF_FOR_GIT=`echo $VSERVERS_CONF/$NAME | sed "s#^/*##"`
79 # Commit the configuration
80 (cd /; git add $CONF_FOR_GIT)
81 (cd /; git commit $CONF_FOR_GIT --edit --message "vserver: Add $NAME vserver configuration.")