ogclone-engine/ogclient/interfaceAdm/CrearImagen.py

110 lines
4.1 KiB
Python

#!/usr/bin/python3
#___________________________________________________
#
# PARAMETROS RECIBIDOS DESDE EL CLIENTE:
# $1 Número de disco
# $2 Número de particion
# $3 Nombre canónico de la imagen (sin extensión)
# $4 Dirección del repositorio (REPO, por defecto)
#___________________________________________________
#$OG_ERR_NOTEXEC Si no es llamada por OG client
#$OG_ERR_LOCKED=4 Si la particion está bloqueada.
#Codigos de error del scripts createImage
#@exception OG_ERR_FORMAT # 1 formato incorrecto.
#@exception OG_ERR_PARTITION # 3 Error en partición de disco o en su sistema de archivos
#@exception OG_ERR_IMAGE # 5 Error en funcion ogCreateImage o ogRestoreImage.
#@exception OG_ERR_NOTWRITE # 14 error de escritura
#@exception OG_ERR_NOTCACHE # 15 si cache no existe 15
#@exception OG_ERR_CACHESIZE # 16 si espacio de la cache local o remota no tiene espacio 16
#@exception OG_ERR_REDUCEFS # 17 error al reducir sistema de archivos.
#@exception OG_ERR_EXTENDFS # 18 Errror al expandir el sistema de archivos.
#Códigos de error de la funcion ogCreateImage
import os
import subprocess
import sys
import time
import ogGlobals
from SystemLib import ogEcho, ogRaiseError
from NetLib import ogGetIpAddress, ogChangeRepo
from StringLib import ogCheckIpAddress
prog = sys.argv[0]
if len (sys.argv) < 4:
ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, 'Incorrect number of arguments')
sys.exit (1)
disk, par, imgname, *other = sys.argv[1:]
arg_repo = other[0] if len (other) > 0 else 'REPO'
dirname = os.path.dirname (prog)
start_time = time.time()
env_boot = os.getenv ('boot')
#Load engine configurator from engine.cfg file.
#Carga el configurador del engine desde el fichero engine.cfg
## (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.OGLOGSESSION, 'w').close()
open (ogGlobals.OGLOGCOMMAND, 'w').close()
open (f"{ogGlobals.OGLOGCOMMAND}.tmp", 'w').close()
# Registro de inicio de ejecución
ogEcho (['log', 'session'], None, f'{ogGlobals.lang.MSG_INTERFACE_START} {prog} {disk} {par} {imgname} {arg_repo}')
# Valor por defecto para el repositorio.
repo = arg_repo
if not repo: repo = 'REPO'
if repo == ogGetIpAddress(): repo = 'CACHE'
# Si es una ip y es distinta a la del recurso samba cambiamos de REPO.
if 'REPO' == repo or StringLib.ogCheckIpAddress (repo):
# Si falla el cambio -> salimos con error repositorio no valido
if not ogChangeRepo (repo):
ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, repo)
sys.exit (1)
# Si el destino es REPO y el cliente no está en modo "admin"; activar repositorio para escritura,
if 'REPO' == repo and 'admin' != env_boot:
retval = subprocess.run ([f'{dirname}/CambiarAcceso.py', 'admin']).returncode
if retval:
sys.exit (retval)
ogEcho ([], None, f'createImage "{disk}" "{par}" "{arg_repo}" /"{imgname}"')
# Si existe, ejecuta script personalizado "createImageCustom"; si no, llama al genérico "createImage".
if os.path.exists ('{ogGlobals.OGSCRIPTS}/createImageCustom.py'):
script = f'{ogGlobals.OGSCRIPTS}/createImageCustom.py'
else:
script = f'{ogGlobals.OGSCRIPTS}/createImage.py'
with open (ogGlobals.OGLOGCOMMAND, 'a') as fd:
p = subprocess.Popen ([script, disk, par, arg_repo, f'/{imgname}'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while p.poll() is None:
for l in iter (p.stdout.readline, b''):
partial = l.decode ('utf-8', 'ignore')
fd.write (partial)
print (partial, end='') ## so that the agent captures out output and reports progress to ogcore
for l in iter (p.stderr.readline, b''):
partial = l.decode ('utf-8', 'ignore')
fd.write (partial)
print (partial, end='')
retval = p.returncode
# Cambiar acceso a modo usuario, si es necesario.
if 'REPO' == repo and 'admin' != env_boot:
subprocess.run ([f'{dirname}/CambiarAcceso.py', 'user'])
# Registro de fin de ejecución
ogEcho (['log', 'session'], None, f'{ogGlobals.lang.MSG_INTERFACE_END} {retval}')
sys.exit (retval)