ogclone-engine/ogclient/scripts/restoreImage.py

119 lines
4.9 KiB
Python

#!/usr/bin/python3
#/**
#@file restoreImage.py
#@brief Script de ejemplo para restaurar una imagen.
#@param $1 Repositorio (CACHE, REPO o dirección IP)
#@param $2 Nombre canónico de la imagen (sin extensión)
#@param $3 Número de disco
#@param $4 Número de particion
#@param $5 Protocolo (UNICAST, UNICAST-DIRECT, MULTICAST o MULTICAST-DIRECT)
#@param $6 Opciones del protocolo
#@ejemplo restoreImage.py REPO imgname 2 2 unicast
#@exception OG_ERR_FORMAT 1 formato incorrecto.
#@exception OG_ERR_NOTFOUND 2 cambio de repositorio: repositorio no encontrado
#@exception OG_ERR_NOTFOUND 2 fichero de imagen o partición no detectados.
#@exception $OG_ERR_MCASTRECEIVERFILE 57 Error en la recepción Multicast de un fichero
#@exception $OG_ERR_PROTOCOLJOINMASTER 60 Error en la conexión de una sesión Unicast|Multicast con el Master
#**/
import os
import os.path
import sys
import re
import time
import ogGlobals
import SystemLib
import NetLib
import StringLib
import FileLib
import ImageLib
import ProtocolLib
t0 = time.time()
prog = os.path.basename (sys.argv[0])
#Load engine configurator from engine.cfg file.
#Carga el configurador del engine desde el fichero engine.cfg
# Valores por defecto: #IMGPROG="partclone" ; #IMGCOMP="lzop" ; #IMGEXT="img" #IMGREDUCE="TRUE"
## (ogGlobals se encarga)
# Clear temporary file used as log track by httpdlog
# Limpia los ficheros temporales usados como log de seguimiento para httpdlog
open (ogGlobals.OGLOGCOMMAND, 'w').close()
if SystemLib.ogGetCaller() not in ['deployImage', 'restoreImageCustom']:
open (ogGlobals.OGLOGSESSION, 'w').close()
SystemLib.ogEcho (['log', 'session'], None, f'[1] {ogGlobals.lang.MSG_SCRIPTS_START} {prog} ({sys.argv})')
# Procesar parámetros de entrada
print (f'argv ({sys.argv}) len ({len (sys.argv)})')
if len (sys.argv) < 5:
SystemLib.ogRaiseError ('session', ogGlobals.OG_ERR_FORMAT, f'{ogGlobals.lang.MSG_FORMAT}: {prog} REPO|CACHE imagen ndisco nparticion [ UNICAST|MULTICAST opciones protocolo]')
sys.exit (1)
_, repo, imgname, disk, par, *other = sys.argv
proto = other[0].upper() if len (other) > 0 else 'UNICAST'
protoopt = other[1] if len (other) > 1 else ''
repo = repo.upper()
# Si MCASTWAIT menos que tiempo de espera del servidor lo aumento
MCASTWAIT = ogGlobals.MCASTWAIT
if ':' in protoopt:
port, wait = protoopt.split (':')
else:
port, wait = ('', '')
if proto.startswith ('MULTICAST') and re.match (r'^-?\d+$', wait):
if int (MCASTWAIT or 0) < int (wait):
MCASTWAIT = int (wait) + 5
imgtype = 'img'
print (f'repo ({repo}) imgname ({imgname}) disk ({disk}) par ({par}) proto ({proto}) protoopt ({protoopt}) MCASTWAIT ({MCASTWAIT})')
# Si es una ip y es igual a la del equipo restaura desde cache
if repo == NetLib.ogGetIpAddress(): repo = 'CACHE'
# Si es una ip y es distinta a la del recurso samba cambiamos de REPO.
if StringLib.ogCheckIpAddress (repo) or 'REPO' == repo:
# Si falla el cambio -> salimos con error repositorio no valido
if not NetLib.ogChangeRepo (repo):
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, repo)
sys.exit (1)
REPO = 'REPO'
# Comprobar que existe la imagen del origen.
imgfile = FileLib.ogGetPath (repo, f'{imgname}.{imgtype}')
imgdir = FileLib.ogGetParentPath (repo, imgname)
print (f'imgfile ({imgfile}) imgdir ({imgdir})')
if not imgfile or not imgdir:
SystemLib.ogRaiseError ('session', ogGlobals.OG_ERR_NOTFOUND, f'{repo}, {imgname}')
sys.exit (1)
# Procesar protocolos de transferencia.
retval = 0
if proto in ['UNICAST', 'UNICAST-DIRECT']:
SystemLib.ogEcho (['log', 'session'], None, f'[40] ogRestoreImage {repo} {imgname} {disk} {par} UNICAST')
retval = SystemLib.ogExecAndLog ('command', ImageLib.ogRestoreImage, repo, imgname, disk, par)
elif proto in ['MULTICAST', 'MULTICAST-DIRECT']:
tool = ImageLib.ogGetImageProgram ('REPO', imgname)
if not tool:
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_IMAGE, f'could not get tool used for image {imgname}')
sys.exit (1)
compress = ImageLib.ogGetImageCompressor ('REPO', imgname)
if not compress:
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_IMAGE, f'could not get compressor used for image {imgname}')
sys.exit (1)
SystemLib.ogEcho (['log', 'session'], None, f'[40] ogMcastReceiverPartition {disk} {par} {port} {tool} {compress}')
if not ProtocolLib.ogMcastRequest (f'{imgname}.img', protoopt):
sys.exit (1)
retval = SystemLib.ogExecAndLog ('command', ProtocolLib.ogMcastReceiverPartition, disk, par, port, tool, compress)
else:
SystemLib.ogRaiseError ('session', ogGlobals.OG_ERR_FORMAT, f'{ogGlobals.lang.MSG_FORMAT}: {prog} REPO|CACHE imagen ndisco nparticion [ UNICAST|MULTICAST opciones protocolo]')
sys.exit (1)
t = time.time() - t0
SystemLib.ogEcho (['log', 'session'], None, f'[100] Duracion de la operacion {int (t/60)}m {int (t%60)}s')
# Código de salida del comando prinicpal de restauración.
sys.exit (not retval) ## negated for the shell