# XenServer virtual machine backup script


# cat vm_backup.script
#!/bin/bash

xenserver_name="$1"
vm_name="$2"
nfs_backup_path="/backup/vm"
email="notifications@lab.net"

function notify {
  date=`/bin/date +"%F-%T"`
  file="/tmp/$date-$vm_name.error"
  /bin/echo "To: $email" > "$file"
  /bin/echo "From: $email" >> "$file"
  /bin/echo "Subject: $1 backup $xenserver_name" >> "$file"
  /bin/echo "" >> "$file"
  /bin/echo "$date $1: $2" >> "$file"
  /usr/sbin/ssmtp $email < $file
  /bin/rm -f $file
}

if [ -f $nfs_backup_path/$vm_name.backup ]; then
  /opt/xensource/bin/xe vm-shutdown name-label=$vm_name
  if [ "$?" -eq "0" ]; then
    /bin/mv $nfs_backup_path/$vm_name.backup $nfs_backup_path/$vm_name.backup.old
    /opt/xensource/bin/xe vm-export vm=$vm_name filename=$nfs_backup_path/$vm_name.backup > /dev/null
    if [ "$?" -eq "0" ]; then
      uuid_1=`/opt/xensource/bin/xe vm-list name-label=$vm_name | /bin/grep uuid | /bin/awk '{print $5}'`
      result="`/opt/xensource/bin/xe vm-import filename=$nfs_backup_path/$vm_name.backup`"
      if [ "`/bin/echo -n "$result" | /bin/grep '-'`" != "" ]; then
        uuid_2=`/opt/xensource/bin/xe vm-list name-label=$vm_name | /bin/grep uuid | /bin/grep -v $uuid_1 | /bin/awk '{print $5}'`
        /opt/xensource/bin/xe vm-uninstall uuid=$uuid_2 force=true
        /opt/xensource/bin/xe vm-start name-label=$vm_name
        if [ "$?" -eq "0" ]; then
          notify "OK" "Backup $vm_name" > /dev/null
        else
          notify "ERROR" "/opt/xensource/bin/xe vm-start name-label=$vm_name" > /dev/null
        fi
      else
        /bin/mv $nfs_backup_path/$vm_name.backup.old $nfs_backup_path/$vm_name.backup
        /opt/xensource/bin/xe vm-start name-label=$vm_name
        notify "ERROR" "/opt/xensource/bin/xe vm-import filename=$nfs_backup_path/$vm_name.backup" > /dev/null
      fi
    else
      /bin/mv $nfs_backup_path/$vm_name.backup.old $nfs_backup_path/$vm_name.backup
      /opt/xensource/bin/xe vm-start name-label=$vm_name
      notify "ERROR" "/opt/xensource/bin/xe vm-export vm=$vm_name filename=$nfs_backup_path/$vm_name.backup" > /dev/null
    fi
  else
    notify "ERROR" "/opt/xensource/bin/xe vm-shutdown name-label=$vm_name" > /dev/null
  fi
else
  notify "ERROR" "$nfs_backup_path/$vm_name.backup does not exist" > /dev/null
fi
# ./vm_backup.script XS01 vserver.lab.net

No comments: