Script para automatizar backups no XenServer

16 02 2010

No outro dia tive necessidade de implementar um script para efectuar backup de várias máquinas virtuais a correr no XenServer 5.5 de uma forma automatizada.

Depois de procurar no google encontrei um já feito neste blog ao qual apenas modifiquei algumas coisas, como não reiniciar as máquinas que estão paradas e certificar-me que este não teria problemas com nomes internacionais.

Sei que alterei mais algumas coisas mas para ser sincero não me recordo.

Trabalho mais com o Xen OSS em Debian mas foi uma maneira de molhar os pés no produto da Citrix.

Fica aqui o script para quem quiser usar sem garantias que não irá destuir o vosso ambiente. Quem quiser usar snapshots ler o comentário sobre o hack para não o usar neste caso – poderia estar mais bem feito e adicionar um argumento ao mesmo para o tipo de backup, mas assim faz o que prentendo para o caso que foi pedido

— CUT HERE —

#!/bin/sh

# XenServer vmbackup v0.3

# Author: Jeff O'Brien, CCA,RHCE

# ITPartners, LLC | Westbrook, ME

# 2009-Sept-24

# Modifications: hteles, SE

# FS | Alfragide, Portugal

# 2010-Feb-10

# hteles ********** Modifications To:

# better handling of filenames; Dont Start Halted VM's; And other Stuff Can't Remember now )

LOGFILE="/var/log/vm-backup.log"

BACKUP_LIST="/root/vm-backup/vm-backup-list.txt"

CLIENTE_ID="Sendys"

BACKUP_DIR="/media/backup/$CLIENTE_ID"

BACKUP_DEV="/dev/hda1"

GET_AVAIL_BACKUP_SPACE="`df -h |grep backup|awk {'print $4'}`"

GET_VM_UUIDS="`xe vm-list |grep uuid|awk {'print $5'}`"

NUM_BKUP_2_KEEP="7"

DOM0_UUID="`xe vm-list |grep -B 1 Control |grep uuid |awk {'print $5'}`"

###################### Install Script################################

install(){

if [ ! -e /media/backup ]; then

mkdir -p /media/backup/$CLIENTE_ID

fi

echo "VM-Backup: Please enter install location [/root/vm-backup]:"

read $INSTALLLOC

if [ "$INSTALLLOC" = "" ]; then

INSTALLLOC="/root/vm-backup"

else

INSTALLLOC="$INSTALLLOC"

fi

#Make install location

echo "INFO: Creating installation location in" $INSTALLLOC

mkdir -p $INSTALLLOC

#Copy files...

echo "INFO: Copying vm-backup file(s) to" $INSTALLLOC

mv vmbackup $INSTALLLOC/

chmod +x $INSTALLLOC/vmbackup

touch /var/log/vm-backup.log

#Build log rotate file

LOGROTATEF=/etc/logrotate.d/vm-backup

touch $LOGROTATEF

echo "/var/log/vm-backup.log {" >> $LOGROTATEF

echo " size 20k" >> $LOGROTATEF

echo " notifempty" >> $LOGROTATEF

echo " create 0600 root root" >> $LOGROTATEF

echo "}" >> $LOGROTATEF

}

##################Build backup file function##############################

build_backup_list(){

#initiate array of uuids as a string... should be all elements

arrayUUID=("$GET_VM_UUIDS")

#Initiate a new array with the removed Domain 0

arrayUUIDfixed=( ${arrayUUID[@]//$DOM0_UUID/} )

echo ${arrayUUIDfixed[@]} > $BACKUP_LIST

}

############################# Backup Function ###############################

backup_images(){

if [ ! -e "$BACKUP_LIST" ]; then

echo "ALERT: Backup file doesn't exist, creating one now..." >> $LOGFILE

build_backup_list

fi

#Begin for loop to parse backup file of uuids to backup

for uuid in `cat $BACKUP_LIST` ;do

#Initiate a couple variables needed along the routine

# //HT Acrescentei as horas também para o caso de haver mais que 1 por dia

# //HT O nome vai stripado

# //HT Vamos usar o nome stripado em vez de ir buscar o param ao XEN

tmpVMNAME="`xe vm-param-get param-name=name-label uuid=$uuid`"

VMNAME=`echo $tmpVMNAME | sed 's/ \+/_/g'`

BKFILENAME=`date +%F-%H-%M`_$VMNAME.xva

POWER_STATE=`xe vm-param-get param-name=power-state uuid=$uuid`

############# STARTING LINE ######################

echo "" >> $LOGFILE

echo "=============================================" >> $LOGFILE

echo "Starting Job for $VMNAME at: `date`" >> $LOGFILE

####################################################

#Do we have a backup directory yet?

echo "INFO: Checking to see if backup directory exists" >> $LOGFILE

if [ -e "$BACKUP_DIR/$VMNAME" ]; then

echo "INFO: VM has backup directory already, skipping creation" >> $LOGFILE

else

mkdir $BACKUP_DIR/$VMNAME

fi

#Routine to find out how many backups exist if any

NUM_BKUPS="`ls $BACKUP_DIR/$VMNAME |wc -l`"

#How many backups are in that directory and does it meet retention policy, if so remove the oldest

if [ "$NUM_BKUPS" -lt "$NUM_BKUP_2_KEEP" ]; then

echo "INFO: Number of backups [$NUM_BKUPS] is less than retention policy, no clean up required" >> $LOGFILE

else

echo "INFO: Cleaning up old backups for " $VMNAME >> $LOGFILE

arrayBackupFiles=(`ls $BACKUP_DIR/$VMNAME`)

echo "INFO: "${arrayBackupFiles[0]} "is the oldest backup and will be DELETED" >> $LOGFILE

rm -rf $BACKUP_DIR/$VMNAME/${arrayBackupFiles[0]}

fi

# //HT - nao queremos snapshot ( Causa Problemas com SQL Server

# Para snapshot mudar o "6.6 -> 5.5

GET_VERS="`cat /etc/redhat-release |grep -c 6.6`"

#echo "INFO: Estado da maquina $VMNAME = $POWER_STATE " >> $LOGFILE

if [ "$GET_VERS" != 1 ]; then

#HT Vamos tentar nao parar maquinas halted:

if [ "$POWER_STATE" != "halted" ]; then

echo "INFO: It seems the fucker $VMNAME is running" >> $LOGFILE

echo "INFO: Stopping Machine $VMNAME" >> $LOGFILE

xe vm-shutdown vm=$uuid

echo "INFO: Stop command completed, waiting 30 secs just in case" >> $LOGFILE

echo "INFO: Running wait event for halted system state on $VMNAME" >> $LOGFILE

sleep 30s

xe event-wait class=vm uuid=$uuid power-state=halted

else

echo "INFO: Machine $VMNAME was already Halted - we will leave it that way" >> $LOGFILE

fi

echo "INFO: Beginning export of $VMNAME to $BACKUP_DIR @ `date +%F-%H:%M`" >> $LOGFILE

echo "Please be Patient Now!!!" >> $LOGFILE

xe vm-export filename=$BACKUP_DIR/$VMNAME/$BKFILENAME vm=$uuid

# hteles Debuging

# Para criar ficheiros vazios comentar a linha anterior e descomentar as duas proximas

# touch $BACKUP_DIR/$VMNAME/$BKFILENAME

# echo $VMNAME $BKFILENAME $uuid > $BACKUP_DIR/$VMNAME/$BKFILENAME

#HT Vamos deixar a maquina no estado anterior após o backup

if [ "$POWER_STATE" != "halted" ]; then

echo "INFO: backup complete" >> $LOGFILE

echo "INFO: Starting $VMNAME" >> $LOGFILE

xe vm-start uuid=$uuid

else

echo "INFO: backup complete" >> $LOGFILE

echo "INFO: Not Starting Previously Halted Machine $VMNAME" >> $LOGFILE

fi

fi

# Backup por SnapShotting ( Causa problemas com SQL SERVER )

if [ "$GET_VERS" = 1 ]; then

echo "INFO: SnapShotting Virtual machine " $VMNAME >> $LOGFILE

SNAPSHOT_UUID="`xe vm-snapshot vm=$VMNAME new-name-label="$VMNAME"_snap`"

xe template-param-set is-a-template=false ha-always-run=false

uuid=$SNAPSHOT_UUID

echo "INFO: Exporting Virtual Machine:" $VMNAME >> $LOGFILE

xe vm-export vm="$VMNAME"_snap filename=$BACKUP_DIR/$VMNAME/$BKFILENAME

echo "INFO: Export Complete, removing backup snapshot" >> $LOGFILE

xe vm-uninstall uuid=$SNAPSHOT_UUID force=true

fi

############## FINISH LINE #####################

echo "Finishing Job for " $VMNAME " at: " `date` >> $LOGFILE

echo "++++++=============================================++++++" >> $LOGFILE

echo "" >> $LOGFILE

###################################################

done

}

######################### Test and if good run backups! ############################

backup(){

MOUNT_TEST="`mount |grep $BACKUP_DEV`"

echo "======================================" >> $LOGFILE

echo " xxxx xxxx eeeeeee nnn nnn" >> $LOGFILE

echo " F E A T H E R" >> $LOGFILE

echo " * " >> $LOGFILE

echo " S Y S T E M S" >> $LOGFILE

echo " xxxx xxxx eeeeeee nnn nn" >> $LOGFILE

echo "======================================" >> $LOGFILE

echo "INFO: Backup jobs are starting, please be patient..." >> $LOGFILE

echo "INFO: Checking if backup is mounted..." >> $LOGFILE

if [ "$MOUNT_TEST" != "" ]; then

echo "SUCCESS: Backup device is mounted" >> $LOGFILE

backup_images

else

echo "INFO: Mounting backup device" >> $LOGFILE

mount $BACKUP_DEV $BACKUP_DIR

if [ $? -eq "0" ]; then

echo "INFO: Mount completed successfully! Continuing" >> $LOGFILE

backup_images

else

echo "INFO: FAILURE to mount backup device exiting..." >> $LOGFILE

exit 1

fi

fi

}

############################## Restore FUnction ##################################

restore(){

echo "RESTORE: Please select an image to restore:"

find $BACKUP_DIR -name *.xva

echo ""

echo -n "Image:"

read IMAGE

echo -n $IMAGE "was selected for restore, continue? [Y/N]:"

read YN

case "$YN" in

Y)

echo $IMAGE "Image is being restored, restoring..."

xe vm-import filename="$IMAGE"

;;

y)

echo $IMAGE "Image is being restored, restoring..."

xe vm-import filename="$IMAGE"

;;

N)

echo $IMAGE "is not being restored, exiting."

exit 1

;;

n)

echo $IMAGE "is not being restored, exiting."

exit 1

;;

*)

echo "Uh ah, you didnt say the magic word."

exit 1

esac

}

# main

case "$1" in

backup)

backup

;;

install)

install

;;

restore)

restore

;;

buildlist)

build_backup_list

;;

*)

clear

echo "vmbackup help - v0.3 jobrien http://virtually-engineered.blogspot.com"

echo "Some modifications by hteles@feather-systems.pt"

echo "https://hteles.wordpress.com"

echo ""

echo "Usage: vmbackup {install|buildlist|backup|restore}"

echo ""

echo "vmbackup is a simple script to assist in your backup routines"

echo "provided on an AS-IS basis"

echo "contact jobrien@itpartnersllc.com for issues"

echo ""

echo "install: installs vmbackup to the install location of your choice,"

echo " creates a logrotate entry and necessary files & folders."

echo ""

echo "buildlist: builds a backup list of UUIDs. This is all inclusive."

echo ""

echo "backup: takes image based backups of VMs listed in vm-backup-list.txt."

echo " built in retention policy of 2 images, oldest is removed."

echo " uses snapshots for 5.5 and halting for 5.0. Pick a window."

echo ""

echo "restore: will list all xva backup images in the backup directory."

echo " type in which file you want to restore and it will be done."

echo ""

echo "Please create your own crontab entry in accordance to your windows."

echo ""

echo "Please update your fstab with the correct device and mountpoint ."

echo ""

exit 1

esac

— CUT HERE —


Ações

Information

5 responses

31 05 2011
live xenserver backup

This is very useful, I think this will come in handy for me at work

5 10 2011
Marllus

Como seria possível adicionar uma versão para backup incremental?

29 03 2012
hteles

olá Marilus.

Estamos a falar de imagens raw, seria difícil efectuar um diff das mesmas.

7 08 2013
Gudrun

This is my first time visit at here and i am truly happy
to read everthing at single place.

7 08 2013
hteles

It’s a very old post, but you’re welcome.

Regards

Deixe uma Resposta

Preencha os seus detalhes abaixo ou clique num ícone para iniciar sessão:

Logótipo da WordPress.com

Está a comentar usando a sua conta WordPress.com Terminar Sessão / Alterar )

Imagem do Twitter

Está a comentar usando a sua conta Twitter Terminar Sessão / Alterar )

Facebook photo

Está a comentar usando a sua conta Facebook Terminar Sessão / Alterar )

Google+ photo

Está a comentar usando a sua conta Google+ Terminar Sessão / Alterar )

Connecting to %s




%d bloggers like this: