Improvements to DevStack's XenServer scripts

I have ensured:
- template gets re-used on second run
- template includes XenServer tools, and custom user accounts
- take snapshot before first boot, for easy re-run
- make host_ip_iface work with either eth2 or eth3
- make ssh into domU checks looser
- above is all ground work for improved jenkins tests
- added some more comments to make it scripts clearer

Change-Id: I5c45370bf8a1393d669480e196b13f592d29154f
diff --git a/tools/xen/scripts/manage-vdi b/tools/xen/scripts/manage-vdi
index a0a27e8..7f12ebc 100755
--- a/tools/xen/scripts/manage-vdi
+++ b/tools/xen/scripts/manage-vdi
@@ -20,6 +20,26 @@
 
 dom0_uuid=$(xe_min vm-list is-control-domain=true)
 
+get_mount_device()
+{
+  vbd_uuid=$1
+
+  dev=$(xe_min vbd-list params=device uuid="$vbd_uuid")
+  if [[ "$dev" =~ "sm/" ]]; then
+    DEBIAN_FRONTEND=noninteractive \
+        apt-get --option "Dpkg::Options::=--force-confold" --assume-yes \
+        install kpartx || true &> /dev/null
+    mapping=$(kpartx -av "/dev/$dev" | sed -ne 's,^add map \([a-f0-9\-]*\).*$,\1,p' | sed -ne "s,^\(.*${part}\)\$,\1,p")
+    if [ -z "$mapping" ]; then
+       echo "Failed to find mapping"
+       exit -1
+    fi
+    echo "mapper/${mapping}"
+  else
+    echo "/dev/$dev$part"
+  fi
+}
+
 open_vdi()
 {
   vbd_uuid=$(xe vbd-create vm-uuid="$dom0_uuid" vdi-uuid="$vdi_uuid" \
@@ -27,26 +47,30 @@
   mp=$(mktemp -d)
   xe vbd-plug uuid="$vbd_uuid"
 
-  udevsettle
-  dev=$(xe_min vbd-list params=device uuid="$vbd_uuid")
-  mount "/dev/$dev$part" "$mp"
+  which_udev=$(which udevsettle) || true
+  if [ -n "$which_udev" ]; then
+      udevsettle
+  else
+      udevadm settle
+  fi
+
+  mount_device=$(get_mount_device "$vbd_uuid")
+  mount "$mount_device" "$mp"
   echo "Your vdi is mounted at $mp"
 }
 
 close_vdi()
 {
   vbd_uuid=$(xe_min vbd-list vm-uuid="$dom0_uuid" vdi-uuid="$vdi_uuid")
-  dev=$(xe_min vbd-list params=device uuid="$vbd_uuid")
-  umount "/dev/$dev$part"
+  mount_device=$(get_mount_device "$vbd_uuid")
+  umount "$mount_device"
 
   xe vbd-unplug uuid=$vbd_uuid
   xe vbd-destroy uuid=$vbd_uuid
 }
 
-if [ "$action" == "open" ]
-then
+if [ "$action" == "open" ]; then
   open_vdi
-elif [ "$action" == "close" ]
-then
+elif [ "$action" == "close" ]; then
   close_vdi
 fi