XenAPI: Fix another race condition

Fix it properly this time by forcing a PID from run.sh and using that to track.

A second issue is that upstart may run services twice, introduce a flock test
to ensure that we only run stack.sh once as running in parallel causes issues.

Change-Id: I05990c7154366350b0f9cc3e6c70d6f34238486f
diff --git a/tools/xen/build_xva.sh b/tools/xen/build_xva.sh
index 7c8e620..7002e6e 100755
--- a/tools/xen/build_xva.sh
+++ b/tools/xen/build_xva.sh
@@ -119,9 +119,7 @@
 
     chown -R $STACK_USER /opt/stack
 
-    if su -c "/opt/stack/run.sh" $STACK_USER; then
-        touch /var/run/devstack.succeeded
-    fi
+    su -c "/opt/stack/run.sh" $STACK_USER
 
     # Update /etc/issue
     {
@@ -177,8 +175,19 @@
 cat <<EOF >$STAGING_DIR/opt/stack/run.sh
 #!/bin/bash
 set -eux
-cd /opt/stack/devstack
-./unstack.sh || true
-./stack.sh
+(
+  flock -n 9 || exit 1
+
+  [ -e /opt/stack/runsh.succeeded ] && rm /opt/stack/runsh.succeeded
+  echo \$\$ >> /opt/stack/run_sh.pid
+
+  cd /opt/stack/devstack
+  ./unstack.sh || true
+  ./stack.sh
+
+  # Got to the end - success
+  touch /opt/stack/runsh.succeeded
+  rm /opt/stack/run_sh.pid
+) 9> /opt/stack/.runsh_lock
 EOF
 chmod 755 $STAGING_DIR/opt/stack/run.sh