#!/bin/bash
#
# Copyright (c) Citrix Systems 2008. All rights reserved.
#
# **
# ** Only run this script if instructed to do so by Citrix support
# **
# Script to wrap a xentrace invocation to log it to a block-attached
# VDI in dom0, so it does not fill up dom0.
# The VDI has the other_config:xentrace flag set to 1, so these can be
# identified later on as xentrace records.
# The VDI contains a ext3 fs (no partition table) and single file "trace.bz2"

TIME=5
SIZE_GB=1
while getopts "ht:s:" opt ; do
    case $opt in
    h)
       echo "Usage: $0 [-t time (sec)] [-s size (GB)]"
       exit 1
    ;;
    t) TIME=$OPTARG
    ;;
    s) SIZE_GB=$OPTARG
    ;;
    *) echo "Invalid option"; exit 1
    ;;
    esac
done

SIZE=$((${SIZE_GB} * 1024 * 1024 * 1024))

if [ ! -e /etc/xensource-inventory ]; then
  echo Must run on a XenServer host.
  exit 1
fi

. /etc/xensource-inventory

XE="@BASE_PATH@/bin/xe"

crashdump_sr=$(${XE} host-list params=crash-dump-sr-uuid --minimal uuid=${INSTALLATION_UUID})

if [ -z "${crashdump_sr}" ]; then
  echo No crashdump storage repository defined for the host.
  exit 1
fi

vdi_date=$(date +%c)
vdi_name="Xentrace results at ${vdi_date}"

echo -n "Creating VDI: "
vdi_uuid=$(${XE} vdi-create sr-uuid=${crashdump_sr} name-label="${vdi_name}" type=system virtual-size=${SIZE})
echo ${vdi_uuid}

if [ $? -ne 0 -o -z "${vdi_uuid}" ]; then
  echo error creating VDI in the crashdump storage repository
  exit 1
fi

${XE} vdi-param-set uuid=${vdi_uuid} other-config:xentrace=1

mnt=
function cleanup {
   if [ ! -z "${vdi_uuid}" ]; then
      ${XE} vdi-destroy uuid=${vdi_uuid}
   fi

   if [ ! -z "${mnt}" ]; then
      umount ${mnt}
      rmdir ${mnt}
   fi

   if [ ! -z "${vbd_uuid}" ]; then
      ${XE} vbd-unplug uuid=${vbd_uuid}
      ${XE} vbd-destroy uuid=${vbd_uuid}
   fi
}

echo -n "Creating VBD: "
vbd_uuid=$(${XE} vbd-create vm-uuid=${CONTROL_DOMAIN_UUID} vdi-uuid=${vdi_uuid} device=autodetect)
echo ${vbd_uuid}

if [ $? -ne 0 -o -z "${vbd_uuid}" ]; then
  echo error creating VBD
  cleanup
  exit 1
fi

echo -n "Plugging VBD: "
${XE} vbd-plug uuid=${vbd_uuid}
device=/dev/$(${XE} vbd-param-get uuid=${vbd_uuid} param-name=device)

if [ ! -b ${device} ]; then
  echo ${device}: not a block special
  cleanup
  exit 1
fi

echo ${device}

echo -n "Creating filesystem: "
mkfs.ext3 -j -F ${device} > /dev/null 2>&1
echo "done"

echo -n "Mounting filesystem: "
mnt=/var/run/crashdump-${vdi_uuid}
mkdir -p ${mnt}

mount ${device} ${mnt}

if [ $? -ne 0 ]; then
  echo mount to ${mnt} failed
  cleanup
  exit 1
fi

echo "done"

echo "Xentrace: starting"
/usr/bin/xentrace -D -e all -r 1 ${mnt}/trace -T ${TIME}

echo "Xentrace: compressing"
bzip2 -9 ${mnt}/trace

echo "Xentrace: done"
echo "Trace recorded to VDI: ${vdi_uuid}"

vdi_uuid=""
cleanup
