Página 1 de 3
[Script] Backup a quente das vm's rodando no XenServer
Enviado: 12 Jun 2014 09:38
por marceloleaes
Segue script para executar backup a quente das vm's rodando em um host XenServer. O ideal é utilizar o mesmo com um HD usb conectado ao host para que a cópia dos arquivos ocorra em uma janela de tempo onde todas as vm's rodando possam ser salvas. Ajuste os campos comentados conforme sua necessidade e depois de validar o funcionamento agende em seu crontab para começar a rodar automaticamente.
NÃO ME RESPONSABILIZO POR PROBLEMAS GERADOS EM SEU HOST, RODE PRIMEIRO EM UM AMBIENTE DE HOMOLOGAÇÃO
Código: Selecionar todos
#!/bin/bash
# Script para backup a quente das vm's do XenServer
# E-tab Tecnologia - [email protected]
# O funcionamento do script é simples. Ele cria um snapshot, converte para template e remove o snapshot
# O envio de emails depende do SendEmail baixe de http://caspian.dotconf.net/menu/Software/SendEmail/
# Jamais rode este script antes de testar seu funcionamento em um host de homologação antes ;)
PATH=/opt/xensource/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
export PATH
BACKDATE=`date +%d-%m-%Y`
# Configurações para o envio de emails
REMETENTE="[email protected]"
ADMIN="[email protected]"
ASSUNTO="XENSERVER - Backup concluido no host $HOSTNAME"
SMTP="smtp.seudominio.com.br"
USUARIO="[email protected]"
SENHA="senhadomail"
# Defina aqui o diretório onde serão salvos os backups
BACKDIR=/mnt/backup/$BACKDATE/$HOSTNAME
echo -e "Resumo das ações realizadas em $HOSTNAME \n" > /tmp/xen_back.mail
if [ -d $BACKDIR ]
then
echo "Diretório de backup já existe"
echo "$BACKDIR Exists" >> /tmp/xen_back.mail
else
echo "Diretório de backup não existe, criando agora."
echo "$BACKDIR não existe, criando agora" >> /tmp/xen_back.mail
mkdir -p $BACKDIR
fi
echo "Gerando lista das VMs rodando no Host"
xe vm-list power-state=running|grep name-label| grep -v "Control domain on host:" | sed 's/ name-label ( RW): //g' > /tmp/xen_back1
echo -e "\n Gerando lista das VMs rodando no Host" >> /tmp/xen_back.mail
cat /tmp/xen_back1 >> /tmp/xen_back.mail
if [ $? -eq 0 ]
then
echo -e "Listagem das VMs concluida com sucesso \n"
echo -e "Listagem das VMs concluida com sucesso \n" >> /tmp/xen_back.mail
else
echo -e "Ocorreu um erro ao obter listagem do Host \n"
echo -e "Ocorreu um erro ao obter listagem do Host \n" >> /tmp/xen_back.mail
fi
VMLIST=`cat /tmp/xen_back1 | wc -l`
COUNT=0
until [ $VMLIST = $COUNT ]
do
COUNT=`expr $COUNT + 1`
VM=`gawk FNR==$COUNT /tmp/xen_back1`
echo "Criando snapshot de $VM"
echo "Criando snapshot de $VM" >> /tmp/xen_back.mail
SNAPSHOT=`xe vm-snapshot vm="$VM" new-name-label="$VM"-$BACKDATE new-name-description="Snapshot Temporário" `
if [ $? -eq 0 ]
then
echo -e "Snapshot da vm $VM criado com sucesso \n"
echo -e "Snapshot da vm $VM criado com sucesso \n" >> /tmp/xen_back.mail
else
echo -e "Ocorreu um erro ao tentar fazer snapshot da vm $VM \n"
echo -e "Ocorreu um erro ao tentar fazer snapshot da vm $VM \n" >> /tmp/xen_back.mail
fi
echo "Convertendo o snapshot $SNAPSHOT da vm $VM para Template"
echo "Convertendo o snapshot $SNAPSHOT da vm $VM para Template" >> /tmp/xen_back.mail
xe template-param-set is-a-template=false uuid=$SNAPSHOT
if [ $? -eq 0 ]
then
echo -e "Conversão do snapshot $SNAPSHOT da vm $VM realizado com sucesso \n"
echo -e "Conversão do snapshot $SNAPSHOT da vm $VM realizado com sucesso \n" >> /tmp/xen_back.mail
else
echo -e "Ocorreu um erro ao tentar converter o snapshot $SNAPSHOT da vm $VM em um Template \n"
echo -e "Ocorreu um erro ao tentar converter o snapshot $SNAPSHOT da vm $VM em um Template \n" >> /tmp/xen_back.mail
fi
echo "Exportando $SNAPSHOT da vm $VM"
echo "Exportando UUID=$SNAPSHOT" >> /tmp/xen_back.mail
xe vm-export vm=$SNAPSHOT filename=$BACKDIR/"$VM".xva compress=true
if [ $? -eq 0 ]
then
echo -e "Processo de conversão do snapshot $SNAPSHOT e backup da vm $VM finalizado com sucesso \n"
echo -e "Processo de conversão do snapshot $SNAPSHOT e backup da vm $VM finalizado com sucesso \n" >> /tmp/xen_back.mail
else
echo -e "Processo de conversão do snapshot $SNAPSHOT para backup da vm $VM não pode ser realizado \n"
echo -e "Processo de conversão do snapshot $SNAPSHOT para backup da vm $VM não pode ser realizado \n" >> /tmp/xen_back.mail
fi
echo "Removendo $SNAPSHOT da vm $VM"
echo "Removendo UUID=$SNAPSHOT">> /tmp/xen_back.mail
xe vm-uninstall uuid=$SNAPSHOT force=true
if [ $? -eq 0 ]
then
echo -e "Remoção do snapshot $SNAPSHOT da vm $VM ocorreu com sucesso \n"
echo -e "Remoção do snapshot $SNAPSHOT da vm $VM ocorreu com sucesso \n" >> /tmp/xen_back.mail
else
echo -e "Ocorreu um erro ao tentar remover $SNAPSHOT vinculado a vm $VM \n"
echo -e "Ocorreu um erro ao tentar remover $SNAPSHOT vinculado a vm $VM \n" >> /tmp/xen_back.mail
fi
echo -e "\n" >> /tmp/xen_back.mail
done
/usr/local/bin/sendEmail -f $REMETENTE -t $ADMIN -u "$ASSUNTO" -o message-file="/tmp/xen_back.mail" -s $SMTP -xu $USUARIO -xp $SENHA
rm -rf /tmp/xen_back*
exit 0
Re:[Script] Backup a quente das vm's rodando no XenServer
Enviado: 12 Jun 2014 12:15
por Elton
Bom dia Marcelo,
Você esse script no próprio xenserver? ele lista todos os hosts do xenserver?
Re:[Script] Backup a quente das vm's rodando no XenServer
Enviado: 12 Jun 2014 12:33
por marceloleaes
No xen, lista as vm's , bate snapshot, converte pra appliance template, salva no lugar especificado.
Re:[Script] Backup a quente das vm's rodando no XenServer
Enviado: 12 Jun 2014 13:01
por Elton
só uma pergunta é que não tenho ambiente de homologação vc usa esse script no seu de produção? se sim amanha já testo no meu kkk empresa pequena é complicado!
Re:[Script] Backup a quente das vm's rodando no XenServer
Enviado: 12 Jun 2014 13:03
por marceloleaes
Uso em produção, porém não recomendo rodar antes de testar.
Tente simular o mesmo ambiente, com o mesmo volume em vhds de preferência. lembrando que o Xen só trabalha com discos fixos, criando o hd ele ja vai estar utilizando o tamanho máximo informado.
Se te atender, aplique no de produção
Re:[Script] Backup a quente das vm's rodando no XenServer
Enviado: 30 Jun 2014 22:42
por Elton
Marcelo testei o script mais no final ele deleta o binario do cat creio que nessa linha rm -rf cat /tmp/xen_back*
Re:[Script] Backup a quente das vm's rodando no XenServer
Enviado: 22 Jul 2014 11:07
por marceloleaes
Putz, foi mal , nem sei porque coloquei aquele cat ali =[
Ajustei no post já pra evitar que alguem mais delete
Re:[Script] Backup a quente das vm's rodando no XenServer
Enviado: 29 Jul 2014 10:59
por leonline
Amigos
Compartilho abaixo o script que utilizo nos meus backups. Este é um script em VB que roda pelo Windows, em qualquer máquina que possua o Xen Center instalado.
Segue abaixo para quem quiser testar.
Código: Selecionar todos
'User configurable variables
'Server names must be seperated by a comma. Names are case sensitive so you have to get the
'name of your server PERFECT!
strServers = "Fileserver"
strUser = "root"
strpw = "password"
strXenServer = "10.1.1.200"
strBackupPath = "E:\Backup\BackupXen"
'Make sure to use the short file name format
strXenCenterPath = "C:\Arquivos de programas\Citrix\XenCenter\"
'Set to TRUE if you want to send a status email or FALSE to not send
binSendEmail = FALSE
strSMTPFrom = "[email protected]"
strSMTPTo = "[email protected]"
strSMTPRelay = "10.1.1.254"
'Number of days to keep the logs and backup files
numKeepLogs = 1
numKeepBackups = 1
'************************************************************************************************
'Do not edit beyond this point
'************************************************************************************************
Dim errStatus, strLogName
Dim fs, logFile
If Right(strBackupPath, 1) = "\" Then
strBackupPath = Left(strBackupPath, Len(strBackupPath) - 1)
End If
If Right(strXenCenterPath, 1) <> "\" Then
strXenCenterPath = strXenCenterPath & "\"
End If
strRunXE = strXenCenterPath & "xe.exe -s " & strXenServer & " -u " & strUser & " -pw " & strpw & " "
arrBackups = Split(strServers, ",")
const ForAppending = 8
errStatus = 0
'Set some global objects
Set WshShell = CreateObject ("Wscript.shell")
'Create the log file and introduction information into log file
Call logSetup
'Check if XenCenter Path is correct
If fs.FileExists(strXenCenterPath & "xe.exe") Then
'Loop through all selected servers and back them up
For iServers = 0 to UBound(arrBackups)
Call backupVM(Trim(arrBackups(iServers)))
Next
Else
writeLog("XenCenter not found, aborting backup!")
errStatus = UBound(arrBackups) + 2
End If
'Finish up the log file
Call logClose
'Send status message via email
Call sendMsg
'Script completed -- REM line below out if you want to run this in a scheduled task
wscript.echo "Backup Concluído!"
Sub backupVM(strServer)
'First, check that the VM exists, and get UUID and name-label information. It is possible to
'name a snapshot as a backup source, but this script does not allow it, so checking for that too
Set objExec = WSHshell.Exec(strRunXE & "vm-list params=uuid,name-label,is-a-snapshot name-label=" & strServer)
strStatus = "Not Found"
Do While Not objExec.StdOut.AtEndOfStream
strStatus = "Found"
strUUID = stripValue(objExec.StdOut.ReadLine())
strVM = stripValue(objExec.StdOut.ReadLine())
strSnapShot = stripValue(objExec.StdOut.ReadLine())
strTemp = objExec.StdOut.ReadLine()
strTemp = objExec.StdOut.ReadLine()
If strSnapShot = "false" and strVM <> "Control domain on host" Then
strStatus = "Good"
End If
Loop
If strStatus = "Not Found" Then
strResult = SetErrorStatus("Add")
writeLog("No VM by that name: " & strServer)
Exit Sub
ElseIf strStatus = "Found" Then
strResult = SetErrorStatus("Add")
writeLog("VM is a Snapshot or Template, no backup performed: " & strServer)
Exit Sub
Else
writeLog("VM Found: " & strServer)
End If
'Remove old backups
writeLog("Cleaning up old backup files")
Set oFolder = fs.GetFolder(strBackupPath)
Set oAllFiles = oFolder.Files
numDM = 0
For Each oFile in oAllFiles
If Left(oFile.Name, 7) = "Backup-" and DateDiff("d", NOW, oFile.DateLastModified) > numKeepBackups Then
numDM = numDM + 1
ReDim Preserve arrFileName(numDM)
arrFileName(numDM) = oFile.Name
fs.DeleteFile oFile.Path
End If
Next
writeLog(numDM & " files deleted")
For x = 1 to numDM
writeLog(" " & arrFileName(x))
Next
'Snapshot the VM
writeLog("Snapshoting server: " & strServer)
Set objExec = WSHshell.Exec(strRunXE & "vm-snapshot new-name-label=" & strServer & "-XenServer-Live-Backup uuid=" & strUUID)
strSSID = objExec.StdOut.ReadLine()
strResult = strSSID
Do While Not objExec.StdOut.AtEndOfStream
strTemp = objExec.StdOut.ReadLine()
writeLog(strTemp)
strResult = strResult & ":" & strTemp
Loop
If InStr(UCase(strResult), "ERROR") Then
writeLog("Error creating snapshot, see above")
Exit Sub
End If
'Set snapshot to NOT be a template
writeLog("Setting snapshot status...")
Set objExec = WSHshell.Exec(strRunXE & "template-param-set is-a-template=false uuid=" & strSSID)
Do While Not objExec.StdOut.AtEndOfStream
writeLog(objExec.StdOut.ReadLine())
Loop
'Export to backup destination
strTime = Replace(Now(), "/", "-")
strTime = Replace(strTime, " ", "-")
strTime = Replace(strTime, ":", "-")
strName = "Backup-" & strServer & "-" & strTime & ".xva"
writeLog("Backup filename: " & strName)
Set objExec = WSHshell.Exec(strRunXE & "vm-export vm=" & strSSID & " filename=" & strBackupPath & "\" & strName)
strResult = ""
Do While Not objExec.StdOut.AtEndOfStream
strTemp = objExec.StdOut.ReadLine()
writeLog(strTemp)
strResult = strResult & ":" & strTemp
Loop
If InStr(UCase(strResult), "SUCCEEDED") = 0 Then
strResult = SetErrorStatus("Add")
writeLog("************** Error during backup of " & strServer & " **************")
End If
'Remove the snapshot
Set objExec = WSHshell.Exec(strRunXE & "vm-uninstall uuid=" & strSSID & " force=true")
strResult = ""
Do While Not objExec.StdOut.AtEndOfStream
strTemp = objExec.StdOut.ReadLine()
writeLog(strTemp)
strResult = strResult & " " & strTemp
Loop
If InStr(strResult, "All objects destroyed") = 0 Then
strResult = SetErrorStatus("Add")
writeLog("**************Error deleting snapshot for " & strServer & " **************")
End If
End Sub
Function stripValue(strValue)
arrStrip = Split(strValue, ":")
stripValue = Trim(arrStrip(1))
End Function
Sub writeLog(strText)
logFile.WriteLine Now() & ": " & strText
End Sub
Function SetErrorStatus(strTask)
If strTask = "Add" Then
errStatus = errStatus + 1
SetErrorStatus = errStatus
Else
numServers = UBound(arrBackups) + 1
If errStatus = 0 Then
SetErrorStatus = "Success"
ElseIf errStatus >= numServers Then
SetErrorStatus = "Failed"
Else
SetErrorStatus = "Partial Failure"
End If
End If
End Function
Sub logSetup
Set fs = CreateObject("Scripting.FileSystemObject")
If Not fs.FolderExists(strBackupPath) Then
fs.CreateFolder(strBackupPath)
End If
Set oFolder = fs.GetFolder(strBackupPath)
Set oAllFiles = oFolder.Files
For Each oFile in oAllFiles
If Left(oFile.Name, 16) = "XenServerBackups" and DateDiff("d", NOW, oFile.DateLastModified) > numKeepLogs Then
fs.DeleteFile oFile.Path
End If
Next
strLogName = "XenServerBackups-" & Replace(Date, "/", "-") & ".log"
Set logFile = fs.OpenTextFile (strBackupPath & "\" & strLogName, ForAppending, True)
logFile.WriteLine "=========================================================================================================="
logFile.WriteLine "Backup for: " & Now()
logFile.WriteLine "=========================================================================================================="
For x = 0 to UBound(arrBackups)
If x = 0 Then
logFile.WriteLine "Servers targeted for backup: " & arrBackups(x)
Else
logFile.WriteLine " " & arrBackups(x)
End If
Next
logFile.WriteLine "Backup User : " & strUser
logFile.WriteLine "Password : *********"
logFile.WriteLine "Xen Server : " & strXenServer
logFile.WriteLine "Backup Destination : " & strBackupPath
logFile.WriteLine
End Sub
Sub logClose
'Finish up the log file
logFile.WriteLine
strStatus = SetErrorStatus("Read")
logFile.WriteLine "Backup completed on " & Now()
logFile.WriteLine "Backup Status: " & strStatus
logFile.WriteLine
logFile.WriteLine
logFile.Close
End Sub
Sub sendMsg
'Send status message via email
If binSendEmail = False Then
Exit Sub
End If
Set oMessage = CreateObject("CDO.Message")
oMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
oMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = strSMTPRelay
oMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
oMessage.Configuration.Fields.Update
strStatus = SetErrorStatus("Read")
oMessage.Subject = "XenServer Backup Completed. Status: " & strStatus & ". Date: " & Now()
oMessage.From = strSMTPFrom
oMessage.To = strSMTPTo
strText = vbCRLF & "XenServer Backup Completed. " & vbCRLF & vbCRLF
strText = strText & "Backup User : " & strUser & vbCRLF
strText = strText & "Password : *********" & vbCRLF
strText = strText & "Xen Server : " & strXenServer & vbCRLF
strText = strText & "Backup Destination : " & strBackupPath & vbCRLF
strText = strText & vbCRLF
strText = strText & "Backup Status : " & strStatus
oMessage.TextBody = strText
oMessage.AddAttachment strBackupPath & "\" & strLogName
oMessage.Send
End Sub
Re:[Script] Backup a quente das vm's rodando no XenServer
Enviado: 29 Jul 2014 22:38
por marceloleaes
Boa
Eu usava um pelo xencenter antes, mas não tão completo como este, vou testar assim que der.
Valeu pela contribuição !
Re:[Script] Backup a quente das vm's rodando no XenServer
Enviado: 01 Ago 2014 09:33
por Elton
Bom dia Marcelão.
qual comando vc usa para realizar o import direto no terminal?
abraços.
Re:[Script] Backup a quente das vm's rodando no XenServer
Enviado: 01 Ago 2014 12:48
por marceloleaes
Direto no xen
Código: Selecionar todos
xe vm-import filename=/mnt/backup/exemplo.xva force=true sr-uuid=UUID do SR preserve=true
Re:[Script] Backup a quente das vm's rodando no XenServer
Enviado: 01 Ago 2014 13:18
por Elton
vlw marcelo. só mais uma dúvida como consigo pegar o uuid do meu sr? abraçosssss
Re:[Script] Backup a quente das vm's rodando no XenServer
Enviado: 01 Ago 2014 14:59
por marceloleaes
Re:[Script] Backup a quente das vm's rodando no XenServer
Enviado: 01 Ago 2014 15:41
por Elton
ai sim hein testei e funfou suaveees man. esquema é importar pela linha de comando mesmo. estava achando que o script estava corrompendo a vm mais está funfando...
Re:[Script] Backup a quente das vm's rodando no XenServer
Enviado: 01 Ago 2014 15:47
por marceloleaes
Realmente, o xencenter é bem bugado tanto para exportar como para importar.
Funciona, mas volta e meia complica por coisas bobas
O XE por linha de comando é tão simples que acabei me acostumando a usar somente ele, auto completa todos os comandos, é ir dando tab e executando o que precisa