Merge "Add ceilometer"
diff --git a/exercises/aggregates.sh b/exercises/aggregates.sh
index 38fac12..8a4f9c1 100755
--- a/exercises/aggregates.sh
+++ b/exercises/aggregates.sh
@@ -7,14 +7,15 @@
 #  *  Updating Aggregate details
 #  *  Testing Aggregate metadata
 #  *  Testing Aggregate delete
-#  *  TODO(johngar) - test adding a host (idealy with two hosts)
+#  *  Testing General Aggregates (https://blueprints.launchpad.net/nova/+spec/general-host-aggregates)
+#  *  Testing add/remove hosts (with one host)
 
 echo "**************************************************"
 echo "Begin DevStack Exercise: $0"
 echo "**************************************************"
 
 # This script exits on an error so that errors don't compound and you see
-# only the first error that occured.
+# only the first error that occurred.
 set -o errexit
 
 # Print the commands being run so that we can see the command that triggers
@@ -47,6 +48,7 @@
 # ===================
 
 AGGREGATE_NAME=test_aggregate_$RANDOM
+AGGREGATE2_NAME=test_aggregate_$RANDOM
 AGGREGATE_A_ZONE=nova
 
 exit_if_aggregate_present() {
@@ -63,6 +65,7 @@
 exit_if_aggregate_present $AGGREGATE_NAME
 
 AGGREGATE_ID=`nova aggregate-create $AGGREGATE_NAME $AGGREGATE_A_ZONE | grep " $AGGREGATE_NAME " | get_field 1`
+AGGREGATE2_ID=`nova aggregate-create $AGGREGATE2_NAME $AGGREGATE_A_ZONE | grep " $AGGREGATE2_NAME " | get_field 1`
 
 # check aggregate created
 nova aggregate-list | grep -q " $AGGREGATE_NAME " || die "Aggregate $AGGREGATE_NAME not created"
@@ -120,13 +123,23 @@
 # Test aggregate-add/remove-host
 # ==============================
 if [ "$VIRT_DRIVER" == "xenserver" ]; then
-    echo "TODO(johngarbutt) add tests for add/remove host from aggregate"
+    echo "TODO(johngarbutt) add tests for add/remove host from pool aggregate"
 fi
-
+HOST=`nova host-list | grep compute | get_field 1`
+# Make sure can add two aggregates to same host
+nova aggregate-add-host $AGGREGATE_ID $HOST
+nova aggregate-add-host $AGGREGATE2_ID $HOST
+if nova aggregate-add-host $AGGREGATE2_ID $HOST; then
+    echo "ERROR could add duplicate host to single aggregate"
+    exit -1
+fi
+nova aggregate-remove-host $AGGREGATE2_ID $HOST
+nova aggregate-remove-host $AGGREGATE_ID $HOST
 
 # Test aggregate-delete
 # =====================
 nova aggregate-delete $AGGREGATE_ID
+nova aggregate-delete $AGGREGATE2_ID
 exit_if_aggregate_present $AGGREGATE_NAME
 
 
diff --git a/functions b/functions
index cd06233..f61aed5 100644
--- a/functions
+++ b/functions
@@ -240,6 +240,30 @@
     export os_VENDOR os_RELEASE os_UPDATE os_PACKAGE os_CODENAME
 }
 
+# git update using reference as a branch.
+function git_update_branch() {
+
+    GIT_BRANCH=$1
+
+    git checkout -f origin/$GIT_BRANCH
+    # a local branch might not exist
+    git branch -D $GIT_BRANCH || true
+    git checkout -b $GIT_BRANCH
+}
+
+
+# git update using reference as a tag. Be careful editing source at that repo
+# as working copy will be in a detached mode
+function git_update_tag() {
+
+    GIT_TAG=$1
+
+    git tag -d $GIT_TAG
+    # fetching given tag only
+    git fetch origin tag $GIT_TAG
+    git checkout -f $GIT_TAG
+}
+
 
 # Translate the OS version values into common nomenclature
 # Sets ``DISTRO`` from the ``os_*`` values
@@ -271,16 +295,16 @@
 
     GIT_REMOTE=$1
     GIT_DEST=$2
-    GIT_BRANCH=$3
+    GIT_REF=$3
 
-    if echo $GIT_BRANCH | egrep -q "^refs"; then
+    if echo $GIT_REF | egrep -q "^refs"; then
         # If our branch name is a gerrit style refs/changes/...
         if [[ ! -d $GIT_DEST ]]; then
             [[ "$ERROR_ON_CLONE" = "True" ]] && exit 1
             git clone $GIT_REMOTE $GIT_DEST
         fi
         cd $GIT_DEST
-        git fetch $GIT_REMOTE $GIT_BRANCH && git checkout FETCH_HEAD
+        git fetch $GIT_REMOTE $GIT_REF && git checkout FETCH_HEAD
     else
         # do a full clone only if the directory doesn't exist
         if [[ ! -d $GIT_DEST ]]; then
@@ -288,7 +312,7 @@
             git clone $GIT_REMOTE $GIT_DEST
             cd $GIT_DEST
             # This checkout syntax works for both branches and tags
-            git checkout $GIT_BRANCH
+            git checkout $GIT_REF
         elif [[ "$RECLONE" == "yes" ]]; then
             # if it does exist then simulate what clone does if asked to RECLONE
             cd $GIT_DEST
@@ -299,10 +323,17 @@
             # (due to the py files having older timestamps than our pyc, so python
             # thinks the pyc files are correct using them)
             find $GIT_DEST -name '*.pyc' -delete
-            git checkout -f origin/$GIT_BRANCH
-            # a local branch might not exist
-            git branch -D $GIT_BRANCH || true
-            git checkout -b $GIT_BRANCH
+
+            # handle GIT_REF accordingly to type (tag, branch)
+            if [[ -n "`git show-ref refs/tags/$GIT_REF`" ]]; then
+                git_update_tag $GIT_REF
+            elif [[ -n "`git show-ref refs/heads/$GIT_REF`" ]]; then
+                git_update_branch $GIT_REF
+            else
+                echo $GIT_REF is neither branch nor tag
+                exit 1
+            fi
+
         fi
     fi
 }
diff --git a/lib/cinder b/lib/cinder
index 49ad4af..796c107 100644
--- a/lib/cinder
+++ b/lib/cinder
@@ -104,11 +104,23 @@
     iniset $CINDER_CONF DEFAULT volume_name_template ${VOLUME_NAME_PREFIX}%s
     iniset $CINDER_CONF DEFAULT iscsi_helper tgtadm
     iniset $CINDER_CONF DEFAULT sql_connection $BASE_SQL_CONN/cinder?charset=utf8
-    iniset $CINDER_CONF DEFAULT rabbit_host $RABBIT_HOST
-    iniset $CINDER_CONF DEFAULT rabbit_password $RABBIT_PASSWORD
     iniset $CINDER_CONF DEFAULT api_paste_config $CINDER_API_PASTE_INI
     iniset $CINDER_CONF DEFAULT root_helper "sudo ${CINDER_ROOTWRAP}"
 
+    if is_service_enabled qpid ; then
+        iniset $CINDER_CONF DEFAULT rpc_backend cinder.openstack.common.rpc.impl_qpid
+    elif [ -n "$RABBIT_HOST" ] &&  [ -n "$RABBIT_PASSWORD" ]; then
+        iniset $CINDER_CONF DEFAULT rabbit_host $RABBIT_HOST
+        iniset $CINDER_CONF DEFAULT rabbit_password $RABBIT_PASSWORD
+    fi
+
+    if [ "$LOG_COLOR" == "True" ] && [ "$SYSLOG" == "False" ]; then
+        # Add color to logging output
+        iniset $CINDER_CONF DEFAULT logging_context_format_string "%(asctime)s %(color)s%(levelname)s %(name)s [%(request_id)s %(user_id)s %(project_id)s%(color)s] %(instance)s%(color)s%(message)s"
+        iniset $CINDER_CONF DEFAULT logging_default_format_string "%(asctime)s %(color)s%(levelname)s %(name)s [-%(color)s] %(instance)s%(color)s%(message)s"
+        iniset $CINDER_CONF DEFAULT logging_debug_format_suffix "from (pid=%(process)d) %(funcName)s %(pathname)s:%(lineno)d"
+        iniset $CINDER_CONF DEFAULT logging_exception_prefix "%(color)s%(asctime)s TRACE %(name)s %(instance)s"
+    fi
 }
 
 # init_cinder() - Initialize database and volume group
diff --git a/stack.sh b/stack.sh
index 1619dfc..2eef0c6 100755
--- a/stack.sh
+++ b/stack.sh
@@ -1137,7 +1137,6 @@
         sudo sed -i -e "s/.*enable_tunneling = .*$/enable_tunneling = $OVS_ENABLE_TUNNELING/g" /$Q_PLUGIN_CONF_FILE
     fi
 
-    iniset /$Q_PLUGIN_CONF_FILE AGENT target_v2_api True
     Q_CONF_FILE=/etc/quantum/quantum.conf
     cp $QUANTUM_DIR/etc/quantum.conf $Q_CONF_FILE
 fi
@@ -1188,7 +1187,7 @@
        # Start up the quantum <-> linuxbridge agent
        # set the default network interface
        QUANTUM_LB_PRIVATE_INTERFACE=${QUANTUM_LB_PRIVATE_INTERFACE:-$GUEST_INTERFACE_DEFAULT}
-       sudo sed -i -e "s/^physical_interface = .*$/physical_interface = $QUANTUM_LB_PRIVATE_INTERFACE/g" /$Q_PLUGIN_CONF_FILE
+       iniset /$Q_PLUGIN_CONF_FILE LINUX_BRIDGE physical_interface_mappings default:$QUANTUM_LB_PRIVATE_INTERFACE
        AGENT_BINARY="$QUANTUM_DIR/quantum/plugins/linuxbridge/agent/linuxbridge_quantum_agent.py"
     fi
 fi
@@ -1238,7 +1237,7 @@
 screen_it q-agt "sudo python $AGENT_BINARY --config-file $Q_CONF_FILE --config-file /$Q_PLUGIN_CONF_FILE"
 
 # Start up the quantum agent
-screen_it q-dhcp "sudo python $AGENT_DHCP_BINARY --config-file=$Q_DHCP_CONF_FILE"
+screen_it q-dhcp "sudo python $AGENT_DHCP_BINARY --config-file $Q_CONF_FILE --config-file=$Q_DHCP_CONF_FILE"
 
 # Nova
 # ----
@@ -1533,7 +1532,7 @@
     # which has some default username and password if you have
     # configured keystone it will checkout the directory.
     if is_service_enabled key; then
-        swift_auth_server+="authtoken keystone"
+        swift_auth_server+="authtoken keystoneauth"
     else
         swift_auth_server=tempauth
     fi
@@ -1563,23 +1562,20 @@
 
     iniset ${SWIFT_CONFIG_PROXY_SERVER} app:proxy-server account_autocreate true
 
-    cat <<EOF>>${SWIFT_CONFIG_PROXY_SERVER}
+    # Configure Keystone
+    sed -i '/^# \[filter:authtoken\]/,/^# \[filter:keystoneauth\]$/ s/^#[ \t]*//' ${SWIFT_CONFIG_PROXY_SERVER}
+    iniset ${SWIFT_CONFIG_PROXY_SERVER} filter:authtoken auth_host $KEYSTONE_AUTH_HOST
+    iniset ${SWIFT_CONFIG_PROXY_SERVER} filter:authtoken auth_port $KEYSTONE_AUTH_PORT
+    iniset ${SWIFT_CONFIG_PROXY_SERVER} filter:authtoken auth_protocol $KEYSTONE_AUTH_PROTOCOL
+    iniset ${SWIFT_CONFIG_PROXY_SERVER} filter:authtoken auth_uri $KEYSTONE_SERVICE_PROTOCOL://$KEYSTONE_SERVICE_HOST:$KEYSTONE_SERVICE_PORT/
+    iniset ${SWIFT_CONFIG_PROXY_SERVER} filter:authtoken admin_tenant_name $SERVICE_TENANT_NAME
+    iniset ${SWIFT_CONFIG_PROXY_SERVER} filter:authtoken admin_user swift
+    iniset ${SWIFT_CONFIG_PROXY_SERVER} filter:authtoken admin_password $SERVICE_PASSWORD
 
-[filter:keystone]
-paste.filter_factory = keystone.middleware.swift_auth:filter_factory
-operator_roles = Member,admin
+    iniuncomment ${SWIFT_CONFIG_PROXY_SERVER} filter:keystoneauth use
+    iniuncomment ${SWIFT_CONFIG_PROXY_SERVER} filter:keystoneauth operator_roles
+    iniset ${SWIFT_CONFIG_PROXY_SERVER} filter:keystoneauth operator_roles "Member, admin"
 
-[filter:authtoken]
-paste.filter_factory = keystone.middleware.auth_token:filter_factory
-auth_host = ${KEYSTONE_AUTH_HOST}
-auth_port = ${KEYSTONE_AUTH_PORT}
-auth_protocol = ${KEYSTONE_AUTH_PROTOCOL}
-auth_uri = ${KEYSTONE_SERVICE_PROTOCOL}://${KEYSTONE_SERVICE_HOST}:${KEYSTONE_SERVICE_PORT}/
-admin_tenant_name = ${SERVICE_TENANT_NAME}
-admin_user = swift
-admin_password = ${SERVICE_PASSWORD}
-delay_auth_decision = 1
-EOF
     if is_service_enabled swift3;then
         cat <<EOF>>${SWIFT_CONFIG_PROXY_SERVER}
 # NOTE(chmou): s3token middleware is not updated yet to use only
@@ -1751,6 +1747,7 @@
 
         # Setup the tgt configuration file
         if [[ ! -f /etc/tgt/conf.d/nova.conf ]]; then
+           sudo mkdir -p /etc/tgt/conf.d
            echo "include $NOVA_DIR/volumes/*" | sudo tee /etc/tgt/conf.d/nova.conf
         fi
 
@@ -2185,6 +2182,8 @@
         RAMDISK=""
         DISK_FORMAT=""
         CONTAINER_FORMAT=""
+        UNPACK=""
+        
         case "$IMAGE_FNAME" in
             *.tar.gz|*.tgz)
                 # Extract ami and aki files
@@ -2216,6 +2215,7 @@
                 IMAGE_NAME=$(basename "$IMAGE" ".img.gz")
                 DISK_FORMAT=raw
                 CONTAINER_FORMAT=bare
+                UNPACK=zcat
                 ;;
             *.qcow2)
                 IMAGE="$FILES/${IMAGE_FNAME}"
@@ -2227,7 +2227,11 @@
         esac
 
         if [ "$CONTAINER_FORMAT" = "bare" ]; then
-            glance --os-auth-token $TOKEN --os-image-url http://$GLANCE_HOSTPORT image-create --name "$IMAGE_NAME" --is-public=True --container-format=$CONTAINER_FORMAT --disk-format $DISK_FORMAT < <(zcat --force "${IMAGE}")
+            if [ "$UNPACK" = "zcat" ]; then
+                glance --os-auth-token $TOKEN --os-image-url http://$GLANCE_HOSTPORT image-create --name "$IMAGE_NAME" --is-public=True --container-format=$CONTAINER_FORMAT --disk-format $DISK_FORMAT <  <(zcat --force "${IMAGE}")
+            else
+                glance --os-auth-token $TOKEN --os-image-url http://$GLANCE_HOSTPORT image-create --name "$IMAGE_NAME" --is-public=True --container-format=$CONTAINER_FORMAT --disk-format $DISK_FORMAT < ${IMAGE}
+            fi
         else
             # Use glance client to add the kernel the root filesystem.
             # We parse the results of the first upload to get the glance ID of the
diff --git a/tools/configure_tempest.sh b/tools/configure_tempest.sh
index 5be709a..d502248 100755
--- a/tools/configure_tempest.sh
+++ b/tools/configure_tempest.sh
@@ -139,9 +139,9 @@
 FLAVORS=""
 for line in $FLAVOR_LINES; do
     if [ -z $DEFAULT_INSTANCE_TYPE ]; then
-        FLAVORS="$FLAVORS `echo $line | grep -v "^\(ID\|+--\)" | cut -d' ' -f2`"
+        FLAVORS="$FLAVORS `echo $line | grep -v "^\(|\s*ID\|+--\)" | cut -d' ' -f2`"
     else
-        FLAVORS="$FLAVORS `echo $line | grep -v "^\(ID\|+--\)" | grep "$DEFAULT_INSTANCE_TYPE" | cut -d' ' -f2`"
+        FLAVORS="$FLAVORS `echo $line | grep -v "^\(|\s*ID\|+--\)" | grep "$DEFAULT_INSTANCE_TYPE" | cut -d' ' -f2`"
     fi
 done
 IFS=" "
diff --git a/tools/xen/build_xva.sh b/tools/xen/build_xva.sh
index fdc6a60..9eae190 100755
--- a/tools/xen/build_xva.sh
+++ b/tools/xen/build_xva.sh
@@ -44,19 +44,14 @@
     exit 1
 fi
 
-# Directory where our conf files are stored
-FILES_DIR=$TOP_DIR/files
-TEMPLATES_DIR=$TOP_DIR/templates
-
-# Directory for supporting script files
-SCRIPT_DIR=$TOP_DIR/scripts
-
-# Version of ubuntu with which we are working
-UBUNTU_VERSION=`cat $STAGING_DIR/etc/lsb-release | grep "DISTRIB_CODENAME=" | sed "s/DISTRIB_CODENAME=//"`
-KERNEL_VERSION=`ls $STAGING_DIR/boot/vmlinuz* | head -1 | sed "s/.*vmlinuz-//"`
-
 # Configure dns (use same dns as dom0)
-cp /etc/resolv.conf $STAGING_DIR/etc/resolv.conf
+# but only when not precise
+if [ "$UBUNTU_INST_RELEASE" != "precise" ]; then
+    cp /etc/resolv.conf $STAGING_DIR/etc/resolv.conf
+elif [ "$MGT_IP" != "dhcp" ] && [ "$PUB_IP" != "dhcp" ]; then
+    echo "Configuration without DHCP not supported on Precise"
+    exit 1
+fi
 
 # Copy over devstack
 rm -f /tmp/devstack.tar
@@ -90,6 +85,7 @@
 
 # Configure the network
 INTERFACES=$STAGING_DIR/etc/network/interfaces
+TEMPLATES_DIR=$TOP_DIR/templates
 cp $TEMPLATES_DIR/interfaces.in  $INTERFACES
 if [ $VM_IP == "dhcp" ]; then
     echo 'eth1 on dhcp'
diff --git a/tools/xen/install_os_domU.sh b/tools/xen/install_os_domU.sh
index 19453c1..0bb6ac8 100755
--- a/tools/xen/install_os_domU.sh
+++ b/tools/xen/install_os_domU.sh
@@ -169,7 +169,7 @@
 HOST_IP=${HOST_IP:-`ifconfig xenbr0 | grep "inet addr" | cut -d ":" -f2 | sed "s/ .*//"`}
 
 # Set up ip forwarding, but skip on xcp-xapi
-if [ -a /etc/sysconfig/network]; then
+if [ -a /etc/sysconfig/network ]; then
     if ! grep -q "FORWARD_IPV4=YES" /etc/sysconfig/network; then
       # FIXME: This doesn't work on reboot!
       echo "FORWARD_IPV4=YES" >> /etc/sysconfig/network
@@ -218,7 +218,7 @@
 #
 
 GUEST_NAME=${GUEST_NAME:-"DevStackOSDomU"}
-TNAME="devstack_template_folsom_11.10"
+TNAME="devstack_template"
 SNAME_PREPARED="template_prepared"
 SNAME_FIRST_BOOT="before_first_boot"
 
@@ -242,19 +242,6 @@
     # Install Ubuntu over network
     #
 
-    # try to find ubuntu template
-    ubuntu_template_name="Ubuntu 11.10 for DevStack (64-bit)"
-    ubuntu_template=$(xe_min template-list name-label="$ubuntu_template_name")
-
-    # remove template, if we are in CLEAN_TEMPLATE mode
-    if [ -n "$ubuntu_template" ]; then
-        if $CLEAN_TEMPLATES; then
-            xe template-param-clear param-name=other-config uuid=$ubuntu_template
-            xe template-uninstall template-uuid=$ubuntu_template force=true
-            ubuntu_template=""
-        fi
-    fi
-
     # always update the preseed file, incase we have a newer one
     PRESEED_URL=${PRESEED_URL:-""}
     if [ -z "$PRESEED_URL" ]; then
@@ -272,13 +259,12 @@
         fi
     fi
 
-    if [ -z "$ubuntu_template" ]; then
-        $TOP_DIR/scripts/xenoneirictemplate.sh $PRESEED_URL
-    fi
+    # Update the template
+    $TOP_DIR/scripts/install_ubuntu_template.sh $PRESEED_URL
 
     # create a new VM with the given template
     # creating the correct VIFs and metadata
-    $TOP_DIR/scripts/install-os-vpx.sh -t "$ubuntu_template_name" -v $VM_BR -m $MGT_BR -p $PUB_BR -l $GUEST_NAME -r $OSDOMU_MEM_MB -k "flat_network_bridge=${VM_BR}"
+    $TOP_DIR/scripts/install-os-vpx.sh -t "$UBUNTU_INST_TEMPLATE_NAME" -v $VM_BR -m $MGT_BR -p $PUB_BR -l $GUEST_NAME -r $OSDOMU_MEM_MB -k "flat_network_bridge=${VM_BR}"
 
     # wait for install to finish
     wait_for_VM_to_halt
diff --git a/tools/xen/prepare_guest.sh b/tools/xen/prepare_guest.sh
index 89a0169..4aa4554 100755
--- a/tools/xen/prepare_guest.sh
+++ b/tools/xen/prepare_guest.sh
@@ -18,6 +18,7 @@
 GUEST_PASSWORD=${GUEST_PASSWORD:-secrete}
 STAGING_DIR=${STAGING_DIR:-stage}
 DO_TGZ=${DO_TGZ:-1}
+XS_TOOLS_PATH=${XS_TOOLS_PATH:-"/root/xs-tools.deb"}
 
 # Install basics
 chroot $STAGING_DIR apt-get update
@@ -26,10 +27,8 @@
 chroot $STAGING_DIR pip install xenapi
 
 # Install XenServer guest utilities
-XEGUEST=xe-guest-utilities_5.6.100-651_amd64.deb
-wget http://images.ansolabs.com/xen/$XEGUEST -O $XEGUEST
-cp $XEGUEST $STAGING_DIR/root
-chroot $STAGING_DIR dpkg -i /root/$XEGUEST
+cp $XS_TOOLS_PATH ${STAGING_DIR}${XS_TOOLS_PATH}
+chroot $STAGING_DIR dpkg -i $XS_TOOLS_PATH
 chroot $STAGING_DIR update-rc.d -f xe-linux-distribution remove
 chroot $STAGING_DIR update-rc.d xe-linux-distribution defaults
 
diff --git a/tools/xen/prepare_guest_template.sh b/tools/xen/prepare_guest_template.sh
index 7c6dec4..60782d0 100755
--- a/tools/xen/prepare_guest_template.sh
+++ b/tools/xen/prepare_guest_template.sh
@@ -44,6 +44,28 @@
     exit 1
 fi
 
+# Copy XenServer tools deb into the VM
+ISO_DIR="/opt/xensource/packages/iso"
+XS_TOOLS_FILE_NAME="xs-tools.deb"
+XS_TOOLS_PATH="/root/$XS_TOOLS_FILE_NAME"
+if [ -e "$ISO_DIR" ]; then
+    TOOLS_ISO=$(ls $ISO_DIR/xs-tools-*.iso)
+    TMP_DIR=/tmp/temp.$RANDOM
+    mkdir -p $TMP_DIR
+    mount -o loop $TOOLS_ISO $TMP_DIR
+    DEB_FILE=$(ls $TMP_DIR/Linux/*amd64.deb)
+    echo "Copying XenServer tools into VM from: $DEB_FILE"
+    cp $DEB_FILE "${STAGING_DIR}${XS_TOOLS_PATH}"
+    umount $TMP_DIR
+    rm -rf $TMP_DIR
+else
+    echo "WARNING: no XenServer tools found, falling back to 5.6 tools"
+    TOOLS_URL="http://images.ansolabs.com/xen/xe-guest-utilities_5.6.100-651_amd64.deb"
+    wget $TOOLS_URL -O $XS_TOOLS_FILE_NAME
+    cp $XS_TOOLS_FILE_NAME "${STAGING_DIR}${XS_TOOLS_PATH}"
+    rm -rf $XS_TOOLS_FILE_NAME
+fi
+
 # Copy prepare_guest.sh to VM
 mkdir -p $STAGING_DIR/opt/stack/
 cp $TOP_DIR/prepare_guest.sh $STAGING_DIR/opt/stack/prepare_guest.sh
@@ -53,5 +75,7 @@
 
 # run prepare_guest.sh on boot
 cat <<EOF >$STAGING_DIR/etc/rc.local
-GUEST_PASSWORD=$GUEST_PASSWORD STAGING_DIR=/ DO_TGZ=0 bash /opt/stack/prepare_guest.sh > /opt/stack/prepare_guest.log 2>&1
+GUEST_PASSWORD=$GUEST_PASSWORD STAGING_DIR=/ \
+    DO_TGZ=0 XS_TOOLS_PATH=$XS_TOOLS_PATH \
+    bash /opt/stack/prepare_guest.sh > /opt/stack/prepare_guest.log 2>&1
 EOF
diff --git a/tools/xen/scripts/install_ubuntu_template.sh b/tools/xen/scripts/install_ubuntu_template.sh
new file mode 100755
index 0000000..f67547b
--- /dev/null
+++ b/tools/xen/scripts/install_ubuntu_template.sh
@@ -0,0 +1,78 @@
+#!/bin/bash
+#
+# This creates an Ubuntu Server 32bit or 64bit template
+# on Xenserver 5.6.x, 6.0.x and 6.1.x
+# The template does a net install only
+#
+# Based on a script by: David Markey <david.markey@citrix.com>
+#
+
+# Exit on errors
+set -o errexit
+# Echo commands
+set -o xtrace
+
+# This directory
+BASE_DIR=$(cd $(dirname "$0") && pwd)
+
+# For default setings see xenrc
+source $BASE_DIR/../xenrc
+
+# Get the params
+preseed_url=$1
+
+# Delete template or skip template creation as required
+previous_template=$(xe template-list name-label="$UBUNTU_INST_TEMPLATE_NAME" \
+    params=uuid --minimal)
+if [ -n "$previous_template" ]; then
+    if $CLEAN_TEMPLATES; then
+        xe template-param-clear param-name=other-config uuid=$previous_template
+        xe template-uninstall template-uuid=$previous_template force=true
+    else
+        echo "Template $UBUNTU_INST_TEMPLATE_NAME already present"
+        exit 0
+    fi
+fi
+
+# Get built-in template
+builtin_name="Debian Squeeze 6.0 (32-bit)"
+builtin_uuid=$(xe template-list name-label="$builtin_name" --minimal)
+if [[ -z $builtin_uuid ]]; then
+    echo "Cant find the Debian Squeeze 32bit template on your XenServer."
+    exit 1
+fi
+
+# Clone built-in template to create new template
+new_uuid=$(xe vm-clone uuid=$builtin_uuid \
+    new-name-label="$UBUNTU_INST_TEMPLATE_NAME")
+
+# Some of these settings can be found in example preseed files
+# however these need to be answered before the netinstall
+# is ready to fetch the preseed file, and as such must be here
+# to get a fully automated install
+pvargs="-- quiet console=hvc0 partman/default_filesystem=ext3 \
+console-setup/ask_detect=false locale=${UBUNTU_INST_LOCALE} \
+keyboard-configuration/layoutcode=${UBUNTU_INST_KEYBOARD} \
+netcfg/choose_interface=${HOST_IP_IFACE} \
+netcfg/get_hostname=os netcfg/get_domain=os auto \
+url=${preseed_url}"
+
+if [ "$NETINSTALLIP" != "dhcp" ]; then
+    netcfgargs="netcfg/disable_autoconfig=true \
+netcfg/get_nameservers=${UBUNTU_INST_NAMESERVERS} \
+netcfg/get_ipaddress=${UBUNTU_INST_IP} \
+netcfg/get_netmask=${UBUNTU_INST_NETMASK} \
+netcfg/get_gateway=${UBUNTU_INST_GATEWAY} \
+netcfg/confirm_static=true"
+    pvargs="${pvargs} ${netcfgargs}"
+fi
+
+xe template-param-set uuid=$new_uuid \
+    other-config:install-methods=http \
+    other-config:install-repository="$UBUNTU_INST_REPOSITORY" \
+    PV-args="$pvargs" \
+    other-config:debian-release="$UBUNTU_INST_RELEASE" \
+    other-config:default_template=true \
+    other-config:install-arch="$UBUNTU_INST_ARCH"
+
+echo "Ubuntu template installed uuid:$new_uuid"
diff --git a/tools/xen/scripts/xenoneirictemplate.sh b/tools/xen/scripts/xenoneirictemplate.sh
deleted file mode 100755
index 7f10c33..0000000
--- a/tools/xen/scripts/xenoneirictemplate.sh
+++ /dev/null
@@ -1,63 +0,0 @@
-#!/bin/bash
-## makeubuntu.sh, this creates Ubuntu server 11.10 32 and 64 bit templates
-## on Xenserver 6.0.2 Net install only
-## Original Author: David Markey <david.markey@citrix.com>
-## Author: Renuka Apte <renuka.apte@citrix.com>
-## This is not an officially supported guest OS on XenServer 6.0.2
-
-BASE_DIR=$(cd $(dirname "$0") && pwd)
-source $BASE_DIR/../../../localrc
-
-LENNY=$(xe template-list name-label=Debian\ Squeeze\ 6.0\ \(32-bit\) --minimal)
-
-if [[ -z $LENNY ]] ; then
-    echo "Cant find Squeeze 32bit template."
-    exit 1
-fi
-
-distro="Ubuntu 11.10 for DevStack"
-arches=("32-bit" "64-bit")
-
-preseedurl=${1:-"http://images.ansolabs.com/devstackubuntupreseed.cfg"}
-
-NETINSTALL_LOCALE=${NETINSTALL_LOCALE:-en_US}
-NETINSTALL_KEYBOARD=${NETINSTALL_KEYBOARD:-us}
-NETINSTALL_IFACE=${NETINSTALL_IFACE:-eth3}
-
-for arch in ${arches[@]} ; do
-    echo "Attempting $distro ($arch)"
-    if [[ -n $(xe template-list name-label="$distro ($arch)" params=uuid --minimal) ]] ; then
-        echo "$distro ($arch)" already exists, Skipping
-    else
-        if [ -z $NETINSTALLIP ]
-        then
-            echo "NETINSTALLIP not set in localrc"
-            exit 1
-        fi
-        # Some of these settings can be found in example preseed files
-        # however these need to be answered before the netinstall
-        # is ready to fetch the preseed file, and as such must be here
-        # to get a fully automated install
-        pvargs="-- quiet console=hvc0 partman/default_filesystem=ext3 locale=${NETINSTALL_LOCALE} console-setup/ask_detect=false keyboard-configuration/layoutcode=${NETINSTALL_KEYBOARD} netcfg/choose_interface=${NETINSTALL_IFACE} netcfg/get_hostname=os netcfg/get_domain=os auto url=${preseedurl}"
-        if [ "$NETINSTALLIP" != "dhcp" ]
-        then
-            netcfgargs="netcfg/disable_autoconfig=true netcfg/get_nameservers=${NAMESERVERS} netcfg/get_ipaddress=${NETINSTALLIP} netcfg/get_netmask=${NETMASK} netcfg/get_gateway=${GATEWAY} netcfg/confirm_static=true"
-            pvargs="${pvargs} ${netcfgargs}"
-        fi
-        NEWUUID=$(xe vm-clone uuid=$LENNY new-name-label="$distro ($arch)")
-        xe template-param-set uuid=$NEWUUID other-config:install-methods=http,ftp \
-         other-config:install-repository=http://archive.ubuntu.net/ubuntu \
-         PV-args="$pvargs" \
-         other-config:debian-release=oneiric \
-         other-config:default_template=true
-
-        if [[ "$arch" == "32-bit" ]] ; then
-            xe template-param-set uuid=$NEWUUID other-config:install-arch="i386"
-        else
-            xe template-param-set uuid=$NEWUUID other-config:install-arch="amd64"
-        fi
-        echo "Success"
-    fi
-done
-
-echo "Done"
diff --git a/tools/xen/xenrc b/tools/xen/xenrc
index 102a492..0365a25 100644
--- a/tools/xen/xenrc
+++ b/tools/xen/xenrc
@@ -1,5 +1,10 @@
 #!/bin/bash
 
+#
+# XenServer specific defaults for the /tools/xen/ scripts
+# Similar to stackrc, you can override these in your localrc
+#
+
 # Name of this guest
 GUEST_NAME=${GUEST_NAME:-DevStackOSDomU}
 
@@ -10,13 +15,18 @@
 # VM Password
 GUEST_PASSWORD=${GUEST_PASSWORD:-secrete}
 
-# Host Interface, i.e. the interface on the nova vm you want to expose the services on
-# Usually either eth2 (management network) or eth3 (public network)
+# Host Interface, i.e. the interface on the nova vm you want to expose the
+# services on. Usually eth2 (management network) or eth3 (public network) and
 # not eth0 (private network with XenServer host) or eth1 (VM traffic network)
+# This is also used as the interface for the Ubuntu install
 HOST_IP_IFACE=${HOST_IP_IFACE:-eth3}
 
+#
 # Our nova host's network info
-VM_IP=${VM_IP:-10.255.255.255} # A host-only ip that let's the interface come up, otherwise unused
+#
+
+# A host-only ip that let's the interface come up, otherwise unused
+VM_IP=${VM_IP:-10.255.255.255}
 MGT_IP=${MGT_IP:-172.16.100.55}
 PUB_IP=${PUB_IP:-192.168.1.55}
 
@@ -38,8 +48,28 @@
 MGT_VLAN=${MGT_VLAN:-101}
 MGT_DEV=${MGT_DEV:-eth0}
 
-# Guest installer network
+# Decide if you should enable eth0,
+# the guest installer network
+# You need to disable this on xcp-xapi on Ubuntu 12.04
 ENABLE_GI=true
 
-# Source params
+# Ubuntu install settings
+UBUNTU_INST_RELEASE="oneiric"
+UBUNTU_INST_TEMPLATE_NAME="Ubuntu 11.10 (64-bit) for DevStack"
+# For 12.04 use "precise" and update template name
+# However, for 12.04, you should be using
+# XenServer 6.1 and later or XCP 1.6 or later
+# 11.10 is only really supported with XenServer 6.0.2 and later
+UBUNTU_INST_ARCH="amd64"
+UBUNTU_INST_REPOSITORY="http://archive.ubuntu.net/ubuntu"
+UBUNTU_INST_LOCALE="en_US"
+UBUNTU_INST_KEYBOARD="us"
+# network configuration for HOST_IP_IFACE during install
+UBUNTU_INST_IP="dhcp"
+UBUNTU_INST_NAMESERVERS=""
+UBUNTU_INST_NETMASK=""
+UBUNTU_INST_GATEWAY=""
+
+# Load stackrc defaults
+# then override with settings from localrc
 cd ../.. && source ./stackrc && cd $TOP_DIR
diff --git a/unstack.sh b/unstack.sh
index 64de915..17752a8 100755
--- a/unstack.sh
+++ b/unstack.sh
@@ -37,7 +37,7 @@
 
 # Swift runs daemons
 if is_service_enabled swift; then
-    swift-init all stop
+    swift-init all stop 2>/dev/null || true
 fi
 
 # Apache has the WSGI processes