Power on/off script for Xen Running VMs on XenServer

Days ago I needed a script to power on/off my runing VMs on XenServer… In my case I needed this to power off VMs when my UPS is running on batery and later to power on when the power comes back.

I was looking for a script that can do the job, but after a while I didn’t find anything usefull… so I made my own script…

My idea was to create a list of all running VMs and power off this VMs. Later, when I need to power on this VMs (from the list) I just call the same script again and it turn on all my VMs that are on this list.

Here is my script (shutdown_xen_vm.sh):

#!/bin/bash

PROGRAMPATH="/root/scr/shutdown_vm"
if [ -f $PROGRAMPATH/vm-list.txt ]
then
   #$PROGRAMPATH/vm-list.txt exist
   echo "Power on:"
   cat $PROGRAMPATH/vm-list.txt | xargs -I{} echo " - {}"
   cat $PROGRAMPATH/vm-list.txt | xargs -I{} xe vm-start vm={}
   echo "Done"
   rm $PROGRAMPATH/vm-list.txt
else
   #$PROGRAMPATH/vm-list.txt do not exist
   xe vm-list power-state=running | grep name-label | awk '{print $4}' | tac | head -n -1 > $PROGRAMPATH/vm-list.txt
   echo "Power off:"
   cat $PROGRAMPATH/vm-list.txt | xargs -I{} echo " - {}"
   cat $PROGRAMPATH/vm-list.txt | xargs -I{} xe vm-shutdown vm={}
   echo "Done"
   echo "Shutdown xen server..."
   shutdown -P now
fi

How it works:

check if file vm-list.txt exist

   if [ -f $PROGRAMPATH/vm-list.txt ]

Just print a list of all VMs that were powered off

   echo "Power on:"
   cat $PROGRAMPATH/vm-list.txt | xargs -I{} echo " - {}"

Start all VMs from the list and delete this list

   cat $PROGRAMPATH/vm-list.txt | xargs -I{} xe vm-start vm={}
   echo "Done"
   rm $PROGRAMPATH/vm-list.txt

Get all running VMs and write it to vm-list.txt

xe vm-list power-state=running | grep name-label | awk '{print $4}' | tac | head -n -1 > /root/scr/shutdown_vm/vm-list.txt

Just print a list of all VMs that will be powered off

   echo "Power off:"
   cat $PROGRAMPATH/vm-list.txt | xargs -I{} echo " - {}"

Power off VMs from the list and shutdown XenServer

   
   cat $PROGRAMPATH/vm-list.txt | xargs -I{} xe vm-shutdown vm={}
   echo "Done"
   echo "Shutdown xen server..."
   shutdown -P now

Now, to run this script you just need to do this:

   
chmod +x shutdown_xen_vm.sh
./shutdown_xen_vm.sh

I hope that this script will help you as it helped me :)

(2) Comments

  • Hector
    28 May 2012

    the xen server that testing does not seem to have root/scr/shutdown_vm , is this a seperate program or is it included in another package

    • Uroš Vovk
      28 May 2012

      Hi,
      “/root/scr/shutdown_vm” (PROGRAMPATH) is just a path to an existing directory and is only needed to store “vm-list.txt”.
      You can change it to some other directory.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.