Stai visualizzando una vecchia versione di questa pagina. Visualizza la versione attuale .

Confronta con corrente Ripristina questa versione Visualizza cronologia

« Precedente Versione 3 Corrente »

 

 

 

 

 ( USO INTERNO )

 

 

 

 

 

 

 

 

 

PREPARATO DA: TOMAŽ CEH     

 

 

 

 

 

 

MAGGIO 2015

1.  Introduzione

 

Questo manuale ha lo scopo di illustrare le procedure e le tecniche utilizzate per implementare un sistema di backup automatico, che sia sicuro e duraturo.

Le procedure che saranno descritte in seguito garantiscono l’integrità dei dati nel caso di crash di sistema o cancellazione involontaria e consentono il loro celere ripristino.

I strumenti di backup sono da applicare alle sole macchine virtuali presenti sui singoli server e non a tutto l’universo aziendale, pertanto dal backup saranno esclusi i singoli utenti.

 

 

2.  Descrizione del sistema

A. Hardware

Di seguito vengono riassunti ( Tabella 1 )  i vari server che ospitano le macchine virtuali e i server di archiviazione dati.

 

Modello

Nome

Processore

Ram

Dischi

Capacità

Raid

Totale

Dell 2950

Freenas1

2x Intel Xeon  5150 @ 2.66 Ghz

16 Gb

6

 

1Tb

 

5

4 Tb

Dell 2950

Freenas2

Intel Xeon  E5310 @ 1.60 Ghz

5Gb

4

2Tb

5

5,2 Tb

Server Cloud Seeweb

Infordatadealers.com

4 vCPU

8Gb

 

 

5

40Gb

Dell R420

Xensrv1

2x Intel Xeon E5-2440 @ 2,40 Ghz  6 core 12 threads

96 Gb

2

1Tb

1

1Tb

Dell R230 II

Xensrv2

Intel i-3 @3240

3.40 Ghs 2 core 4 threads

32 Gb

2

 

256Gb

1

256Gb

Qnap

Ts-269L

Qnap

Intel Atom 1,86Ghz

1 Gb

2

4 Tb

1

4Tb

Tabella 1: Tabella riepilogativa Server

Dalla tabella si evince che i due server principali sono Xenserver1 e Xenserver2. Entrambe le macchine  sono di recente fabbricazione e si distinguono prevalentemente per la potenza di calcolo ( maggiore nel Xenserver1 ) e per la quantità di ram installata.

Xenserver1 è il server di riferimento per le macchine virtuali invece Xenserver2 è usato prevalentemente per scopi secondari, garantendo comunque prestazioni elevate avendo due dischi SSD Samung evo 840 da 256 GB ciascuno con configurazione Raid 1 per garantirne l’affidabilità.

I server per l’archiviazione e la gestione dei dati sono tre: due server fisici convertiti in nas e un nas nativo. Tra i tre Freenas2 e quello con la maggior capacità di memorizzazione, ovvero quattro dischi da 2 Tb ciascuno configurati in Raid 5 per una capacità totale di 5,2 Tb 

B. Software

Si è scelto di utizzare XenServer come sistema per la virtualizzazione delle macchine virtuali. Xenserver e un prodotto della Citrix, azienda Americana operante nel campo delle tecnologie per la virtualizzazione desktop e server, networking, cloud computing e Software as a Service (SaaS )

Il prodotto XenServer è rilasciato sotto la licenza GPL ovvero è un prodotto open source con feature a pagamento. Nel caso dell’azienda Infordata Sistemi si è scelto di utilizzare solamente la componente opensource in quanto le esigenze aziendali non necessitano di una licenza avanzata.

I due server convertiti in nas utilizzano il sistema operativo Freenas versione

Vediamo ora in dettaglio ( Tabella 2 ) le varie macchine virtuali con i corrispettivi sistemi operativi.

Nome VM

Sistema operativo

Versione

 Server

APPSRV

UBUNTU

14.04 LTS

XEN_1

ARIETE DEV

WINDOWS SERVER 2008 R2

ENTERPRISE

XEN_1

ARIETE LIVE

WINDOWS SERVER 2008 R2

ENTERPRISE

XEN_2

ASTERISKS PSIT

UBUNTU

12.00

XEN_1

DBSRV

UBUNTU

14.04 LTS

XEN_2

ISP-MAILSRV

UBUNTU

14.04 LTS

XEN_1

ISP-WEBSRV

UBUNTU

14.04.02 LTS

XEN_1

JIRA

UBUNTU

12.00

XEN_2

JIRA-SRV

UBUNTU

12.00

XEN_1

MeetMe App Server

UBUNTU

14.04 LTS

XEN_1

MIKROTIK

UBUNTU

?

XEN_1

NETSRV

UBUNTU

12.04.4 LTS

XEN_1

PDC-2012

WINDOWS SERVER 2012 R2

STANDARD

XEN_1

PDC2012-DC2

WINDOWS SERVER 2012 R2

STANDARD

XEN_2

PROXY

UBUNTU

14.04 LTS

XEN_1

STORAGE-2012

WINDOWS SERVER 2012 R2

STANDARD

XEN_1

TERMINALSRV-

2012

WINDOWS SERVER 2012 R2

STANDARD

XEN_1

VIDEOSRV-2012

WINDOWS SERVER 2012 R2

STANDARD

XEN_1

WEBSRV

UBUNTU

10.04

XEN_1

WEBSRV-

TERAMO

UBUNTU

14.04 LTS

XEN_2

WEBSRV-

DELSUS

UBUNTU

14.04 LTS

XEN_2

Tabella 2 Tabella riepilogativa macchine virtuali

3.  Strategie di Backup

Al fine di garantire una maggiore affidabilità dei sistemi di backup , si è scelto di diversificare le strategie di salvataggio in base alla specificità del sistema. Di seguito sono descritti i vari sistemi: macchine virtualidatabase e siti internet.

 Backup delle macchine virtuali:  Avendo adottato il sistema Citrix Xenserver 6.1  per la virtualizzazione si è in grado di gestire numerose macchine virtuali utilizzando solamente due server host ( Xensrv1 e Xensrv2 ).

I server e i dati sono contenuti in due server convertiti in Nas ( Freenas1 e Freenas2 ).  La procedura di backup consiste nel fotografare ( procedura di snapshot ) i vari sistemi . Questo consente di ripristinare il sistema alle condizioni in cui si trovava prima del salvataggio. La procedura è pertanto svincolata dal hardware in quanto si può ripristinare il sistema anche su un server differente a patto che quest’ultimo sia di uguale o superiore potenza. Lo script che è impiegato converte lo snapshot in tamplate. Come unità di archiviazione per i backup si è scelto il NAS Qnap TS-269L  con due dischi da 3 Tb  configurati in RAID 1. Come file di sistema  si è scelto il NFS. 

La procedura si basa sullo script snapback.sh ( creato in python ) sviluppato da Mark Round e successivamente modificato da Luis Davim. Per il corretto backup delle macchine virtuali bisogna apportare le seguenti modifiche su ogni singola macchina, ovvero aggiungere i custom field come segue:

  • Backup - formato testo
  • Retrive - formato testo 
  • xva_backup - formato testo
  • xva_retain - formato testo
  • suspend - formato testo

In primo parametro backup può avere i seguenti valori: daily, weekly e monthly. La cadenza dei backup può essere rispettivamente giornaliera, settimanale o mensile.

Il parametro Retrive specifica quanti snapshot vanno mantenuti escludendo lo snapshot corrente. Settandolo a "2" si avranno in totale 3 backup ( lo snapshot corrente e "2" vecchi )

Xva_backup e xva_retain sono rispettivamente la cadenza con cui viene creata ed esportata la macchina virtuale con estensione xva e quanti file xva della singola macchina vanno mantenuti.

Suspend se settato su 1 sospende la macchina virtuale.

Vediamo ora in dettaglio alcune voci dello script snapback ( Allegato A ) che devono essere modificate per renderlo funzionante sul server nel quele verra importato e successivamente eseguito.

Le righe che vanno modificate sono le seguenti:

?       TEMPLATE_SR=ca02fbf3-c677-1c02-756b-d382b2b58a29    

?       XVA_SR="snapback"

?       NFS_EXPORT="192.168.120.15:/Backup"

 

Template SR - specifica l'UUID della Storage Repository NFS. L'UUID è una chiave univoca a 16byte ( 128 bit ) che viene associata alla Storage Repository nel momento della sua creazione. Nel nostro caso si riferisce al NAS Qnap TS-269L ( ip: 192.168.120.15 ) 

XVA_SR - specifica il nome della cartella nella quale verranno salvati i file XVA. Si è scelto   snapback per XenSrv1 e snapback2 per Xensrv2

       NFS_EXPORT="192.168.120.15:/Backup" - specifica xxx dove verrà salvato il tamplate previamente creato

Lo script cosi modificato va importato in : root/usr/local/bin/   e bisogna aggiungere la seguente riga al crontab ( root/etc/crontab ):

02 22 * * * root /usr/local/bin/snapback.sh > /var/log/snapback.log 2>&1

Il primo e il secondo numero specificano rispettivamente il minuto e l'ora di esecuzione dello script, nel nostro caso le 22h e 02 minuti. Gli altri asterischi indicano una cadenza giornaliera. 

Come si può notare durante l’esecuzione dello script viene creato anche un log che verrà salvato in /var/log/snapback.log

 

Database:

XXXXXXXXXXXXXXXXXXXXXXXXXXXX

 


4.  Pianificazione dei salvataggi

Il salvataggio degli snapshot delle macchine virtuali è regolata in base alla loro criticità. Vengono di seguito illustrati con l'ausilio di tabelle le cadenze per ogni macchina virtuale. 

Snapshots xensrv1

 

Risorsa

Giornaliero

Settimanale

Mensile

APPSRV

x

 

 

ARIETE DEV

x

 

 

ASTERISKS PSIT

x

 

 

  ISP-MAILSRV

x

 

 

ISP-WEBSRV

x

 

 

JIRA-SRV

 

 

 

MeetMe App Server

x

 

 

MIKROTIK

 

 

 

NETSRV

 

x

 

PDC-2012

 

x

 

PROXY

 

 

 

STORAGE-2012

 

 

      x

TERMINALSRV-

2012

 

x

 

VIDEOSRV-2012

 

x

 

WEBSRV

 

 

 

Tabella 3 Pianificazione snapshot su Xensrv 1

 

Snapshot xensrv2

 

Risorsa

Giornaliero

Settimanale

Mensile

ARIETE LIVE

x

 

 

DBSRV

x

 

 

JIRA

x

 

 

PDC2012-DC2

x

x

 

WEBSRV-

TERAMO

x

 

 

WEBSRV-

DELSUS

x

 

 

 

 

 

 

Tabella 4 Pianificazione snapshot su Xensrv2

Dalle due tabelle si può constatare che quasi tutte le macchine virtuali vengono backuppate ogni giorno. Mentre solo alcune ( di grosse dimensioni come Storage-2012 e VideoSrv-2012 ) vengono backupati solo i fine settimana.

Lo script permette anche  l’esportazione dello snapshot in formato  *.xva sul qnap  questa opzione coincide con la creazione dello snapshot-template giornaliero o settimanale.

5.  Ripristino dei dati

Il ripristino dei dati si differenzia per i vari sistemi:

  • Macchine virtuali
  • Database

Di seguito vengono approfonditi i vari aspetti per ogni realtà.

A. Macchine virtuali ( VM )

Le operazioni di ripristino vengono eseguite tramite XenCenter e consistono nell’ importare ( o se già presente) il template sul server di destinazione.   Se il template è già presente nel server , questo va selezionato col tasto destro del mouse e va selezionata la prima voce, ovvero “New VM wizard…”       

e seguendo lo wizard si potrà creare una nuova macchina virtuale perfettamente funzionante.

 

Tabella 5 Wizard template

 

 

 

 

Riepilogo figure

 

Tabella 1: Tabella riepilogativa Server. 4

Tabella 2 Tabella riepilogativa macchine virtuali 5

Tabella 3 Pianificazione snapshot su Xensrv 1. 8

Tabella 4 Pianificazione snapshot su Xensrv2. 8

Tabella 5 Wizard template. 9

 

 

Allegato A

 

#!/bin/bash

# snapback.sh 1.4

# Simple script to create regular snapshot-based backups for Citrix Xenserver

# Mark Round, scripts@markround.com

# http://www.markround.com/snapback

#

# 1.4 : Modifications by Luis Davim to support XVA backups with independent scheduling

# 1.3 : Added basic lockfile

# 1.2 : Tidied output, removed VDIs before deleting snapshots and templates

# 1.1 : Added missing force=true paramaters to snapshot uninstall calls.

#For more info on XenServer backups read:

# http://docs.vmd.citrix.com/XenServer/6.0.0/1.0/en_gb/reference.html#backups

#

# Variables

#

#Backup only running VMs or every VM?

ONLY_RUNNING="True"

#Oraganize backups in folders?

USE_FOLDERS="True"

FOLDER_RETAIN="1"

# Temporary snapshots will be use this as a suffix

SNAPSHOT_SUFFIX=snapback

# Temporary backup templates will use this as a suffix

TEMP_SUFFIX=newbackup

# Backup templates will use this as a suffix, along with the date

BACKUP_SUFFIX=backup

# What day to run weekly backups on

WEEKLY_ON="Sat"

# What day to run monthly backups on. These will run on the first day

# specified below of the month.

MONTHLY_ON="Sat"

# Temporary file

TEMP=/tmp/snapback.$$

# UUID of the destination SR for backups

TEMPLATE_SR=b8f6aced-11ac-727e-1326-3fcac58f6189

# UUID of the destination SR for XVA files it must be an NFS SR

#XVA_SR=6d3e3b3a-23f8-0441-8f85-5c414c588497

XVA_SR="snapback"

#Suspend VM or create a snapshot

SUSPEND=0

POWERSTATE=""

#NFS Export

NFS_EXPORT="192.168.120.15:/Backup"

#MOUNT_PATH="/var/run/sr-mount"

MOUNT_PATH="/backup"

LOCKFILE=/tmp/snapback.lock

#Cicle control flags

SKIP_TEMPLATE=1

SKIP_XVA=1

COUNT=0

if [ -f $LOCKFILE ]; then

        echo "Lockfile $LOCKFILE exists, exiting!"

        exit 1

fi

touch $LOCKFILE

#

# Don't modify below this line

#

 

#Check if mount point exists

if [ ! -d "$MOUNT_PATH" ]; then

    echo "Mount point does not exist, I'm going to create it.'"

    mkdir -p "$MOUNT_PATH"

fi

#check if moint point is mounted

mount | grep "$MOUNT_PATH" > /dev/null

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

    echo "== NFS already mounted, unmounting... =="

    umount $MOUNT_PATH;

fi

#Mout NFS share

echo "== Mounting NFS share =="

mount -t nfs -o hard $NFS_EXPORT $MOUNT_PATH

 

# Date format must be %Y%m%d so we can sort them

BACKUP_DATE=$(date +"%Y%m%d")

# Quick hack to grab the required paramater from the output of the xe command

function xe_param()

{

    PARAM=$1

    while read DATA; do

        LINE=$(echo $DATA | egrep "$PARAM")

        if [ $? -eq 0 ]; then

            echo "$LINE" | awk 'BEGIN{FS=": "}{print $2}'

        fi

    done

}

# Deletes a snapshot's VDIs before uninstalling it. This is needed as

# snapshot-uninstall seems to sometimes leave "stray" VDIs in SRs

function delete_snapshot()

{

    DELETE_SNAPSHOT_UUID=$1

    for VDI_UUID in $(xe vbd-list vm-uuid=$DELETE_SNAPSHOT_UUID empty=false | xe_param "vdi-uuid"); do

            echo "Deleting snapshot VDI : $VDI_UUID"

            xe vdi-destroy uuid=$VDI_UUID

    done

    # Now we can remove the snapshot itself

    echo "Removing snapshot with UUID : $DELETE_SNAPSHOT_UUID"

    xe snapshot-uninstall uuid=$DELETE_SNAPSHOT_UUID force=true

}

# See above - templates also seem to leave stray VDIs around...

function delete_template()

{

    DELETE_TEMPLATE_UUID=$1

    for VDI_UUID in $(xe vbd-list vm-uuid=$DELETE_TEMPLATE_UUID empty=false | xe_param "vdi-uuid"); do

            echo "Deleting template VDI : $VDI_UUID"

            xe vdi-destroy uuid=$VDI_UUID

    done

    # Now we can remove the template itself

    echo "Removing template with UUID : $DELETE_TEMPLATE_UUID"

    xe template-uninstall template-uuid=$DELETE_TEMPLATE_UUID force=true

}

function rescan_srs()

{

    echo "Rescanning SRs..."

    # Get all SRs

    SRS=$(xe sr-list | xe_param uuid)

    for SR in $SRS; do

        echo "Scanning SR: $SR"

        xe sr-scan uuid=$SR

    done

    echo "  Done - $(date)"

    echo " "

}

 

echo " "

echo "=== Snapshot backup started at $(date) ==="

echo " "

if [ "$ONLY_RUNNING" == "True" ]; then

    # Get all running VMs

    RUNNING_VMS=$(xe vm-list power-state=running is-control-domain=false | xe_param uuid)

else

    RUNNING_VMS=$(xe vm-list is-control-domain=false | xe_param uuid)

fi

for VM in $RUNNING_VMS; do

    VM_NAME="$(xe vm-list uuid=$VM | xe_param name-label)"

    # Useful for testing, if we only want to process one VM

    #if [ "$VM_NAME" != "testvm" ]; then

    #    continue

    #fi

    echo " "

    echo "== Backup for $VM_NAME started at $(date) =="

    echo "= Retrieving backup paramaters ="

    #Template backups

    SCHEDULE=$(xe vm-param-get uuid=$VM param-name=other-config param-key=XenCenter.CustomFields.backup)

    RETAIN=$(xe vm-param-get uuid=$VM param-name=other-config param-key=XenCenter.CustomFields.retain)

    #XVA Backups

    XVA_SCHEDULE=$(xe vm-param-get uuid=$VM param-name=other-config param-key=XenCenter.CustomFields.xva_backup)

    XVA_RETAIN=$(xe vm-param-get uuid=$VM param-name=other-config param-key=XenCenter.CustomFields.xva_retain)

    SUSPEND=$(xe vm-param-get uuid=$VM param-name=other-config param-key=XenCenter.CustomFields.suspend)

    # Not using this yet, as there are some bugs to be worked out...

    # QUIESCE=$(xe vm-param-get uuid=$VM param-name=other-config param-key=XenCenter.CustomFields.quiesce)

##############################check Template schedule###########################

    SKIP_TEMPLATE=1

    if [[ "$SCHEDULE" == "" || "$RETAIN" == "" ]]; then

        echo "No schedule or retention set for template backup, skipping this VM"

        SKIP_TEMPLATE=1

    else

        echo "VM template backup schedule : $SCHEDULE"

        echo "VM template retention       : $RETAIN previous snapshots"

        if [ "$SCHEDULE" == "daily" ]; then

            SKIP_TEMPLATE=0

        else

            # If weekly, see if this is the correct day

            if [ "$SCHEDULE" == "weekly" ]; then

                if [ "$(date +'%a')" == "$WEEKLY_ON" ]; then

                    echo "On correct day for weekly backups, running..."

                    SKIP_TEMPLATE=0

                else

                    echo "Weekly backups scheduled on $WEEKLY_ON, skipping..."

                    SKIP_TEMPLATE=1

                fi

            else

                # If monthly, see if this is the correct day

                if [ "$SCHEDULE" == "monthly" ]; then

                    if [[ "$(date +'%a')" == "$MONTHLY_ON" && $(date '+%e') -le 7 ]]; then

                        echo "On correct day for monthly backups, running..."

                        SKIP_TEMPLATE=0

                    else

                        echo "Monthly backups scheduled on 1st $MONTHLY_ON, skipping..."

                        SKIP_TEMPLATE=1

                    fi

                fi

            fi

        fi

    fi

##############################check XVA schedule################################

    SKIP_XVA=1

    if [[ "$XVA_SCHEDULE" == "" || "$XVA_RETAIN" == "" ]]; then

        echo "No schedule or retention set for XVA backup, skipping this VM"

        SKIP_XVA=1

    else

        echo "VM XVA backup schedule : $XVA_SCHEDULE"

        echo "VM XVA retention       : $XVA_RETAIN previous snapshots"

        if [ "$XVA_SCHEDULE" == "daily" ]; then

            SKIP_XVA=0

        else

            # If weekly, see if this is the correct day

            if [ "$XVA_SCHEDULE" == "weekly" ]; then

                if [ "$(date +'%a')" == "$WEEKLY_ON" ]; then

                    echo "On correct day for weekly backups, running..."

                    SKIP_XVA=0

                else

                    echo "Weekly backups scheduled on $WEEKLY_ON, skipping..."

                    SKIP_XVA=1

                fi

            else

                # If monthly, see if this is the correct day

                if [ "$XVA_SCHEDULE" == "monthly" ]; then

                    if [[ "$(date +'%a')" == "$MONTHLY_ON" && $(date '+%e') -le 7 ]]; then

                        echo "On correct day for monthly backups, running..."

                        SKIP_XVA=0

                    else

                        echo "Monthly backups scheduled on 1st $MONTHLY_ON, skipping..."

                        SKIP_XVA=1

                    fi

                fi

            fi

        fi

    fi

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

    if [[ "$SKIP_TEMPLATE" == "1" && "$SKIP_XVA" == "1" ]]; then

        echo "Nothing to do for this VM!..."

        continue

    fi

    echo "= Checking snapshots for $VM_NAME - $(date) ="

    VM_SNAPSHOT_CHECK=$(xe snapshot-list name-label="$VM_NAME-$SNAPSHOT_SUFFIX" | xe_param uuid)

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

        echo "Found old backup snapshot : $VM_SNAPSHOT_CHECK"

        echo "Deleting..."

        delete_snapshot $VM_SNAPSHOT_CHECK

    fi

    echo "  Done - $(date)"

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

        echo "= Creating snapshot backup - $(date) ="

        # Select appropriate snapshot command

        # See above - not using this yet, as have to work around failures

        #if [ "$QUIESCE" == "true" ]; then

        #    echo "Using VSS plugin"

        #    SNAPSHOT_CMD="vm-snapshot-with-quiesce"

        #else

        #    echo "Not using VSS plugin, disks will not be quiesced"

        #    SNAPSHOT_CMD="vm-snapshot"

        #fi

        SNAPSHOT_CMD="vm-snapshot"

        SNAPSHOT_UUID=$(xe $SNAPSHOT_CMD vm="$VM_NAME" new-name-label="$VM_NAME-$SNAPSHOT_SUFFIX")

        echo "Created snapshot with UUID : $SNAPSHOT_UUID"

    else

        # Check that it's running

        POWERSTATE=$(xe vm-param-get uuid=$VM param-name=power-state)

        if [[ ${POWERSTATE} == "running" ]]; then

            echo "Suspending VM..."

            xe vm-suspend uuid=$VM

        fi

        SNAPSHOT_UUID=$VM

    fi

    #Backup to template ################################################

    if [ "$SKIP_TEMPLATE" == "0" ]; then

        echo "= Copying snapshot to SR - $(date) ="

        # Check there isn't a stale template with TEMP_SUFFIX name hanging around from a failed job

        TEMPLATE_TEMP="$(xe template-list name-label="$VM_NAME-$TEMP_SUFFIX" | xe_param uuid)"

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

            echo "Found a stale temporary template, removing UUID $TEMPLATE_TEMP"

            delete_template $TEMPLATE_TEMP

        fi

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

            COPY_CMD="snapshot-copy"

        else

            COPY_CMD="vm-copy"

        fi

        TEMPLATE_UUID=$(xe $COPY_CMD uuid=$SNAPSHOT_UUID sr-uuid=$TEMPLATE_SR new-name-description="Snapshot created on $(date)" new-name-label="$VM_NAME-$TEMP_SUFFIX")

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

            xe vm-param-set uuid=$TEMPLATE_UUID is-a-template=true

        fi

        echo "  Done - $(date)"

        # Check there is no template with the current timestamp.

        # Otherwise, you would not be able to backup more than once a day if you needed...

        TODAYS_TEMPLATE="$(xe template-list name-label="$VM_NAME-$BACKUP_SUFFIX-$BACKUP_DATE" | xe_param uuid)"

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

            echo "Found a template already for today, removing UUID $TODAYS_TEMPLATE"

            delete_template $TODAYS_TEMPLATE

        fi

        echo "= Renaming template - $(date) ="

        xe template-param-set name-label="$VM_NAME-$BACKUP_SUFFIX-$BACKUP_DATE" uuid=$TEMPLATE_UUID

        echo "  Done - $(date)"

        # List templates for all VMs, grep for $VM_NAME-$BACKUP_SUFFIX

        # Sort -n, head -n -$RETAIN

        # Loop through and remove each one

        echo "= Removing old template backups - $(date) ="

        xe template-list | grep "$VM_NAME-$BACKUP_SUFFIX" | xe_param name-label | sort -n | head -n-$RETAIN > $TEMP

        while read OLD_TEMPLATE; do

            OLD_TEMPLATE_UUID=$(xe template-list name-label="$OLD_TEMPLATE" | xe_param uuid)

            echo "Removing : $OLD_TEMPLATE with UUID $OLD_TEMPLATE_UUID"

            delete_template "$OLD_TEMPLATE_UUID"

        done < "$TEMP"

    fi

    #Backup to XVA #####################################################

    if [ "$SKIP_XVA" == "0" ]; then

        #check if a XVA file with the current timestamp exists

        if [ "$USE_FOLDERS" == "True" ]; then

            mkdir -p "$MOUNT_PATH/$XVA_SR/$BACKUP_DATE-$BACKUP_SUFFIX"

            FNAME="$MOUNT_PATH/$XVA_SR/$BACKUP_DATE-$BACKUP_SUFFIX/$VM_NAME.xva"

        else

            FNAME="$MOUNT_PATH/$XVA_SR/$VM_NAME-$BACKUP_SUFFIX-$BACKUP_DATE.xva"

        fi

        if [ -e "$FNAME" ]; then

            echo "Found a XVA already for today, removing it"

            rm -f "$FNAME"

        fi

        echo "= Exporting VM to file - $(date) ="

        #Creates a XVA file from the snapshot

        EXPORT_CMD="vm-export"

        xe $EXPORT_CMD vm=$SNAPSHOT_UUID filename="$FNAME"

        echo "  Done - $(date)"

        # List XVA files for all VMs, grep for $VM_NAME-$BACKUP_SUFFIX

        # Sort -n, head -n -$XVA_RETAIN

        # Loop through and remove each one

        echo "= Removing old XVA files - $(date) ="

        if [ "$USE_FOLDERS" != "True" ]; then

            ls -1 $MOUNT_PATH/$XVA_SR/*.xva | grep "$VM_NAME-$BACKUP_SUFFIX" | sort -n | head -n-$XVA_RETAIN > $TEMP

            while read OLD_TEMPLATE; do

                echo "Removing : $OLD_TEMPLATE"

                rm "$OLD_TEMPLATE"

            done < $TEMP

        fi

    fi

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

        echo "= Removing temporary snapshot backup ="

        delete_snapshot $SNAPSHOT_UUID

        echo "  Done - $(date)"

    else

        # If the VM was previously running resume it

        if [[ ${POWERSTATE} == "running" ]]; then

          echo "Resuming VM..."

          xe vm-resume uuid=$VM

          echo "  Done - $(date)"

        fi

    fi

    echo "== Backup for $VM_NAME finished at $(date) =="

    echo " "

    sleep 1

    #Rescan SRs every 3 backups to release space allocated by deleted snapshots

    if [ "$COUNT" == "3" ]; then

        COUNT=0

        rescan_srs

    else

        COUNT=$((COUNT+1))

    fi

    sleep 3

done

#Clear old XVA backups

if [ "$USE_FOLDERS" == "True" ]; then

    ls -1 $MOUNT_PATH/$XVA_SR/ | grep "$BACKUP_SUFFIX" | sort -n | head -n-$FOLDER_RETAIN > $TEMP

    while read OLD_TEMPLATE; do

        echo "Removing : $OLD_TEMPLATE"

        rm -rf "$MOUNT_PATH/$XVA_SR/$OLD_TEMPLATE"

    done < $TEMP

fi

xe vdi-list sr-uuid=$TEMPLATE_SR > $MOUNT_PATH/$XVA_SR/mapping.txt

xe vbd-list > $MOUNT_PATH/$XVA_SR/vbd-mapping.txt

echo "=== Snapshot backup finished at $(date) ==="

echo " "

echo "=== Metadata backup started at $(date) ==="

echo " "

#Backup Pool meta-data:

#/opt/xensource/bin/xe-backup-metadata -c -k 10 -u $TEMPLATE_SR

xe pool-dump-database file-name=$MOUNT_PATH/$XVA_SR/pool_metadata

#to restore metadata use:

# xe pool-restore-database file-name=<backup> # there is an option to test the backup with dry-run=true

echo "=== Metadata backup finished at $(date) ==="

echo " "

rescan_srs

if [ "$(date +'%a')" == "$WEEKLY_ON" ]; then

    echo "On correct day for weekly backups, running coalesce_leaf.sh..."

    /usr/local/sbin/coalesce_leaf.sh

fi

sleep 5

#unmount NFS share

echo "== Unmounting NFS share =="

umount $MOUNT_PATH;

rm $LOCKFILE

rm $TEMP