refs #1672 add interfaceAdm/CrearImagen.py
parent
f8eaf8859a
commit
7165dd552a
|
@ -7,7 +7,6 @@ from NetLib import ogChangeRepo
|
||||||
|
|
||||||
parser = argparse.ArgumentParser (add_help=False)
|
parser = argparse.ArgumentParser (add_help=False)
|
||||||
parser.add_argument ('ip_repo')
|
parser.add_argument ('ip_repo')
|
||||||
parser.add_argument ('og_unit', nargs='?', default=None)
|
|
||||||
|
|
||||||
if 2 == len (sys.argv) and 'help' == sys.argv[1]:
|
if 2 == len (sys.argv) and 'help' == sys.argv[1]:
|
||||||
#parser.print_help() sale en inglés aunque la locale indique otra cosa
|
#parser.print_help() sale en inglés aunque la locale indique otra cosa
|
||||||
|
@ -16,7 +15,7 @@ if 2 == len (sys.argv) and 'help' == sys.argv[1]:
|
||||||
|
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
ret = ogChangeRepo (args.ip_repo, args.og_unit)
|
ret = ogChangeRepo (args.ip_repo)
|
||||||
if ret is not None:
|
if ret is not None:
|
||||||
if ret == True: sys.exit (0)
|
if ret == True: sys.exit (0)
|
||||||
elif ret == False: sys.exit (1)
|
elif ret == False: sys.exit (1)
|
||||||
|
|
|
@ -1,54 +1,62 @@
|
||||||
#!/usr/bin/env python3
|
#!/usr/bin/python3
|
||||||
|
|
||||||
|
#______________________________________
|
||||||
|
#
|
||||||
|
# PARAMETROS RECIBIDOS DESDE EL CLIENTE
|
||||||
|
# $1 modo (admin, user)
|
||||||
|
#______________________________________
|
||||||
|
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
|
import re
|
||||||
import subprocess
|
import subprocess
|
||||||
import NetLib
|
|
||||||
import SystemLib
|
|
||||||
|
|
||||||
def main():
|
import ogGlobals
|
||||||
if len(sys.argv) != 2:
|
from SystemLib import ogEcho, ogRaiseError, ogIsRepoLocked
|
||||||
print("Usage: CambiarAcceso.py <mode>")
|
from NetLib import ogGetRepoIp
|
||||||
sys.exit(1)
|
|
||||||
|
|
||||||
mode = sys.argv[1]
|
# Error si llamada no se realliza desde OpenGnsys Client.
|
||||||
repo_ip = NetLib.ogGetRepoIp()
|
prog = sys.argv[0]
|
||||||
|
if len (sys.argv) != 2:
|
||||||
|
print (f'Usage: {prog} <mode>')
|
||||||
|
sys.exit (1)
|
||||||
|
|
||||||
if not repo_ip:
|
# Salir si el repositorio está bloquedo (tiene ficheros abiertos).
|
||||||
SystemLib.ogRaiseError("OG_ERR_NOTFOUND", "repo no montado")
|
mode = sys.argv[1]
|
||||||
|
repoip = ogGetRepoIp()
|
||||||
|
if not repoip:
|
||||||
|
ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, 'repo no montado')
|
||||||
|
sys.exit (1)
|
||||||
|
if ogIsRepoLocked():
|
||||||
|
ogRaiseError ([], ogGlobals.OG_ERR_LOCKED, f'repo {repoip}')
|
||||||
|
sys.exit (1)
|
||||||
|
|
||||||
if SystemLib.ogIsRepoLocked():
|
# Comprobar protocolo y modo de acceso.
|
||||||
SystemLib.ogRaiseError("OG_ERR_LOCKED", f"repo {repo_ip}")
|
proto = os.getenv ('ogprotocol', 'smb')
|
||||||
|
if proto not in ['nfs', 'smb']:
|
||||||
|
ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, f'protocolo desconocido {proto}')
|
||||||
|
sys.exit (1)
|
||||||
|
if 'admin' == mode: mount_mode = 'rw'
|
||||||
|
elif 'user' == mode: mount_mode = 'ro'
|
||||||
|
else:
|
||||||
|
ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, f'modo desconocido {mode}')
|
||||||
|
sys.exit (1)
|
||||||
|
|
||||||
proto = os.getenv("ogprotocol", "smb")
|
# Desmontar repositorio y volver a montarlo con el modo adecuado.
|
||||||
if proto not in ["nfs", "smb"]:
|
subprocess.run (['umount', ogGlobals.OGIMG])
|
||||||
SystemLib.ogRaiseError("OG_ERR_FORMAT", f"protocolo desconocido {proto}")
|
ogEcho ([], 'info', f'Montar repositorio {repoip} por {proto} en modo {mode}')
|
||||||
|
if 'nfs' == proto:
|
||||||
if mode == "admin":
|
subprocess.run (['mount', '-t', 'nfs', f'{repoip}:{ogGlobals.OGIMG}', ogGlobals.OGIMG, '-o', mount_mode])
|
||||||
mount_mode = "rw"
|
elif 'smb' == proto:
|
||||||
elif mode == "user":
|
pass_option = ''
|
||||||
mount_mode = "ro"
|
with open ('/scripts/ogfunctions', 'r') as fd:
|
||||||
else:
|
while True:
|
||||||
SystemLib.ogRaiseError("OG_ERR_FORMAT", f"modo desconocido {mode}")
|
line = fd.readline()
|
||||||
|
if not line: break
|
||||||
OGIMG = os.getenv("OGIMG", "/mnt/OGIMG")
|
if not re.search ('^[\t ]*(export )?OPTIONS=', line): continue
|
||||||
OGUNIT = os.getenv("OGUNIT", "")
|
m = re.search (r'pass=(\w*)', line)
|
||||||
if OGUNIT:
|
if m:
|
||||||
OGUNIT = f"/{OGUNIT}"
|
pass_option = m.groups (0)[0]
|
||||||
|
break
|
||||||
subprocess.run(["umount", OGIMG], check=True)
|
if not pass_option: pass_option = 'og'
|
||||||
SystemLib.ogEcho("info", f"Montar repositorio {repo_ip} por {proto} en modo {mode}")
|
subprocess.run (['mount.cifs', f'//{repoip}/ogimages', ogGlobals.OGIMG, '-o', f'{mount_mode},serverino,acl,username=opengnsys,password={pass_option}'])
|
||||||
|
|
||||||
if proto == "nfs":
|
|
||||||
subprocess.run(["mount", "-t", "nfs", f"{repo_ip}:{OGIMG}{OGUNIT}", OGIMG, "-o", mount_mode], check=True)
|
|
||||||
elif proto == "smb":
|
|
||||||
with open("/scripts/ogfunctions", "r") as f:
|
|
||||||
for line in f:
|
|
||||||
if "OPTIONS=" in line:
|
|
||||||
pass_option = line.split("pass=")[1].split()[0]
|
|
||||||
break
|
|
||||||
else:
|
|
||||||
pass_option = "og"
|
|
||||||
subprocess.run(["mount.cifs", f"//{repo_ip}/ogimages{OGUNIT}", OGIMG, "-o", f"{mount_mode},serverino,acl,username=opengnsys,password={pass_option}"], check=True)
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
|
|
|
@ -1,74 +1,109 @@
|
||||||
#!/usr/bin/env python3
|
#!/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 os
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
import time
|
import time
|
||||||
import NetLib
|
|
||||||
import ogGlobals
|
import ogGlobals
|
||||||
|
from SystemLib import ogEcho, ogRaiseError
|
||||||
|
from NetLib import ogGetIpAddress, ogChangeRepo
|
||||||
|
from StringLib import ogCheckIpAddress
|
||||||
|
|
||||||
def load_engine_config():
|
prog = sys.argv[0]
|
||||||
engine_config_path = "/opt/opengnsys/etc/engine.cfg"
|
if len (sys.argv) < 4:
|
||||||
if os.path.exists(engine_config_path):
|
ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, 'Incorrect number of arguments')
|
||||||
with open(engine_config_path) as f:
|
sys.exit (1)
|
||||||
exec(f.read(), globals())
|
disk, par, imgname, *other = sys.argv[1:]
|
||||||
|
arg_repo = other[0] if len (other) > 0 else 'REPO'
|
||||||
|
dirname = os.path.dirname (prog)
|
||||||
|
|
||||||
def clear_temp_logs():
|
start_time = time.time()
|
||||||
open(os.getenv('OGLOGSESSION'), 'w').close()
|
env_boot = os.getenv ('boot')
|
||||||
open(os.getenv('OGLOGCOMMAND'), 'w').close()
|
|
||||||
open(f"{os.getenv('OGLOGCOMMAND')}.tmp", 'w').close()
|
|
||||||
|
|
||||||
def log_session_start(script_name, args):
|
#Load engine configurator from engine.cfg file.
|
||||||
SystemLib.ogEcho("log session", f"{os.getenv('MSG_INTERFACE_START')} {script_name} {' '.join(args)}")
|
#Carga el configurador del engine desde el fichero engine.cfg
|
||||||
|
## (ogGlobals se encarga)
|
||||||
|
|
||||||
def log_session_end(retval):
|
# Clear temporary file used as log track by httpdlog
|
||||||
SystemLib.ogEcho("log session", f"{os.getenv('MSG_INTERFACE_END')} {retval}")
|
# 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()
|
||||||
|
|
||||||
def ogCheckIpAddress(ip):
|
# Registro de inicio de ejecución
|
||||||
try:
|
ogEcho (['log', 'session'], None, f'{ogGlobals.lang.MSG_INTERFACE_START} {prog} {disk} {par} {imgname} {arg_repo}')
|
||||||
subprocess.check_call(["ping", "-c", "1", ip])
|
|
||||||
return 0
|
|
||||||
except subprocess.CalledProcessError:
|
|
||||||
return 1
|
|
||||||
|
|
||||||
def create_image(disk_num, partition_num, repo, image_name):
|
# Valor por defecto para el repositorio.
|
||||||
if subprocess.call(["which", "createImageCustom"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) == 0:
|
repo = arg_repo
|
||||||
return subprocess.call(["createImageCustom", disk_num, partition_num, repo, f"/{image_name}"])
|
if not repo: repo = 'REPO'
|
||||||
else:
|
if repo == ogGetIpAddress(): repo = 'CACHE'
|
||||||
return subprocess.call(["createImage", disk_num, partition_num, repo, f"/{image_name}"])
|
# 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)
|
||||||
|
|
||||||
def main():
|
# Si el destino es REPO y el cliente no está en modo "admin"; activar repositorio para escritura,
|
||||||
if len(sys.argv) != 5:
|
if 'REPO' == repo and 'admin' != env_boot:
|
||||||
sys.exit(SystemLib.ogRaiseError(OG_ERR_FORMAT, "Incorrect number of arguments"))
|
retval = subprocess.run ([f'{dirname}/CambiarAcceso.py', 'admin']).returncode
|
||||||
|
if retval:
|
||||||
|
sys.exit (retval)
|
||||||
|
|
||||||
disk_num, partition_num, image_name, repo = sys.argv[1:5]
|
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'
|
||||||
|
|
||||||
start_time = time.time()
|
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
|
||||||
|
|
||||||
load_engine_config()
|
# Cambiar acceso a modo usuario, si es necesario.
|
||||||
clear_temp_logs()
|
if 'REPO' == repo and 'admin' != env_boot:
|
||||||
log_session_start(sys.argv[0], sys.argv[1:])
|
subprocess.run ([f'{dirname}/CambiarAcceso.py', 'user'])
|
||||||
|
|
||||||
repo = repo if repo else "REPO"
|
# Registro de fin de ejecución
|
||||||
if repo == NetLib.ogGetIpAddress():
|
ogEcho (['log', 'session'], None, f'{ogGlobals.lang.MSG_INTERFACE_END} {retval}')
|
||||||
repo = "CACHE"
|
|
||||||
|
|
||||||
if ogCheckIpAddress(repo) == 0 or repo == "REPO":
|
sys.exit (retval)
|
||||||
OGUNIT = os.getenv('OGUNIT', "")
|
|
||||||
if not NetLib.ogChangeRepo(repo, OGUNIT):
|
|
||||||
sys.exit(SystemLib.ogRaiseError(OG_ERR_NOTFOUND, f"{repo}"))
|
|
||||||
|
|
||||||
if repo == "REPO" and os.getenv('boot') != "admin":
|
|
||||||
retval = CambiarAcceso("admin")
|
|
||||||
if retval > 0:
|
|
||||||
sys.exit(retval)
|
|
||||||
|
|
||||||
retval = create_image(disk_num, partition_num, repo, image_name)
|
|
||||||
|
|
||||||
if repo == "REPO" and os.getenv('boot') != "admin":
|
|
||||||
CambiarAcceso("user")
|
|
||||||
|
|
||||||
log_session_end(retval)
|
|
||||||
sys.exit(retval)
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
|
|
|
@ -233,7 +233,7 @@ def ogCreateImage (disk, par, container, imgfile, tool='partclone', level='gzip'
|
||||||
|
|
||||||
bn = os.path.basename (imgfile)
|
bn = os.path.basename (imgfile)
|
||||||
IMGFILE = f'{imgdir}/{bn}.{imgtype}'
|
IMGFILE = f'{imgdir}/{bn}.{imgtype}'
|
||||||
if ogIsImageLocked (IMGFILE):
|
if ogIsImageLocked (container=None, imgfile=IMGFILE):
|
||||||
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_LOCKED, f'{ogGlobals.lang.MSG_IMAGE} {container}, {imgfile}')
|
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_LOCKED, f'{ogGlobals.lang.MSG_IMAGE} {container}, {imgfile}')
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
|
@ -39,48 +39,32 @@ def _ogConnect (server, protocol, src, dst, options, readonly):
|
||||||
#@param 2 Abreviatura Unidad Organizativa
|
#@param 2 Abreviatura Unidad Organizativa
|
||||||
#@return Cambio recurso remoto en OGIMG.
|
#@return Cambio recurso remoto en OGIMG.
|
||||||
#*/
|
#*/
|
||||||
def ogChangeRepo(ip_repo, og_unit=None):
|
def ogChangeRepo (ip_repo):
|
||||||
ogprotocol = os.environ['ogprotocol'] or 'smb'
|
ogprotocol = os.environ.get ('ogprotocol', 'smb')
|
||||||
|
|
||||||
if og_unit:
|
|
||||||
SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_GENERIC, 'the og_unit parameter became unsupported')
|
|
||||||
return None
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
mount = subprocess.run (['mount'], capture_output=True, text=True).stdout
|
mount = subprocess.run (['mount'], capture_output=True, text=True).stdout
|
||||||
ro = bool (list (filter (lambda line: re.search (r'ogimages.*\bro,', line), mount.splitlines())))
|
ro = bool (list (filter (lambda line: re.search (r'ogimages.*\bro,', line), mount.splitlines())))
|
||||||
|
|
||||||
current_repo = ogGetRepoIp()
|
current_repo = ogGetRepoIp()
|
||||||
new_repo = current_repo if ip_repo.upper() == "REPO" else ip_repo
|
new_repo = current_repo if ip_repo.upper() == 'REPO' else ip_repo
|
||||||
if new_repo == current_repo: return True
|
if new_repo == current_repo: return True
|
||||||
|
|
||||||
subprocess.run(["umount", ogGlobals.OGIMG], check=True)
|
subprocess.run (['umount', ogGlobals.OGIMG], check=True)
|
||||||
|
|
||||||
SystemLib.ogEcho (['session', 'log'], None, f'{ogGlobals.lang.MSG_HELP_ogChangeRepo} {new_repo}')
|
SystemLib.ogEcho (['session', 'log'], None, f'{ogGlobals.lang.MSG_HELP_ogChangeRepo} {new_repo}')
|
||||||
options = _ogConnect_options()
|
options = _ogConnect_options()
|
||||||
if not _ogConnect (new_repo, ogprotocol, 'ogimages', ogGlobals.OGIMG, options, ro):
|
if not _ogConnect (new_repo, ogprotocol, 'ogimages', ogGlobals.OGIMG, options, ro):
|
||||||
_ogConnect (current_repo, ogprotocol, 'ogimages', ogGlobals.OGIMG, options, ro)
|
_ogConnect (current_repo, ogprotocol, 'ogimages', ogGlobals.OGIMG, options, ro)
|
||||||
SystemLib.ogRaiseError(
|
SystemLib.ogRaiseError ('session', ogGlobals.OG_ERR_REPO, f'Error connecting to the new repository: {new_repo}')
|
||||||
"session",
|
|
||||||
ogGlobals.OG_ERR_REPO,
|
|
||||||
f"Error connecting to the new repository: {new_repo}",
|
|
||||||
)
|
|
||||||
return False
|
return False
|
||||||
|
|
||||||
SystemLib.ogEcho(
|
SystemLib.ogEcho (['session', 'log'], None, f'Repository successfully changed to {new_repo}'.strip())
|
||||||
["session", "log"],
|
|
||||||
None,
|
|
||||||
f"Repository successfully changed to {new_repo}".strip(),
|
|
||||||
)
|
|
||||||
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
SystemLib.ogRaiseError(
|
SystemLib.ogRaiseError ('session', ogGlobals.OG_ERR_GENERIC, f'Error executing ogChangeRepo: {e}')
|
||||||
"session",
|
|
||||||
ogGlobals.OG_ERR_GENERIC,
|
|
||||||
f"Error executing ogChangeRepo: {e}",
|
|
||||||
)
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
#/**
|
#/**
|
||||||
|
|
Loading…
Reference in New Issue