refs #1597 #1605 add Configurar.py

code-review
Natalia Serrano 2025-02-25 09:25:01 +01:00
parent 7c9fbc014f
commit cc17975a43
2 changed files with 163 additions and 109 deletions

View File

@ -1,147 +1,189 @@
#!/usr/bin/env python3
#!/usr/bin/python3
import os
import sys
import subprocess
import ogGlobals
import SystemLib
import CacheLib
import FileSystemLib
import DiskLib
# Load engine configurator from engine.cfg file.
og_engine_configurate = os.getenv('OGENGINECONFIGURATE')
if not og_engine_configurate:
with open('/opt/opengnsys/client/etc/engine.cfg') as f:
for line in f:
if '=' in line:
key, value = line.strip().split('=', 1)
os.environ[key] = value
print(f"{key}={value}")
#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
og_log_session = os.getenv('OGLOGSESSION')
og_log_command = os.getenv('OGLOGCOMMAND')
open (ogGlobals.OGLOGSESSION, 'w').close()
open (ogGlobals.OGLOGCOMMAND, 'w').close()
open (ogGlobals.OGLOGCOMMAND+'.tmp', 'w').close()
if og_log_session:
# Check if the file exists, if not create it
if not os.path.exists(og_log_session):
os.makedirs(os.path.dirname(og_log_session), exist_ok=True)
with open(og_log_session, 'w') as f:
f.write(" ")
else:
with open(og_log_session, 'w') as f:
f.write(" ")
print("og_log_command", og_log_command)
if og_log_command:
with open(og_log_command, 'w') as f:
f.write(" ")
with open(f"{og_log_command}.tmp", 'w') as f:
f.write(" ")
print("og_log_session", og_log_session)
# Registro de inicio de ejecución
def SystemLib.ogEcho(log_type, message):
# Implement the logging function here
pass
print("os.getenv('MSG_INTERFACE_START')", os.getenv('MSG_INTERFACE_START'))
msg_interface_start = os.getenv('MSG_INTERFACE_START')
if msg_interface_start:
SystemLib.ogEcho('log', f"session {msg_interface_start} {__name__} {' '.join(os.sys.argv[1:])}")
SystemLib.ogEcho (['log', 'session'], None, f'{ogGlobals.lang.MSG_INTERFACE_START} {sys.argv}')
# Solo ejecutable por OpenGnsys Client.
path = os.getenv('PATH')
if path:
os.environ['PATH'] = f"{path}:{os.path.dirname(__name__)}"
#path = os.getenv('PATH')
#if path:
# os.environ['PATH'] = f"{path}:{os.path.dirname(__name__)}"
prog = os.path.basename(__name__)
print("prog", prog)
#____________________________________________________________________
#
# El parámetro $2 es el que aporta toda la información y el $1 se queda obsoleto
# Formato de entrada:
# dis=Número de disco
# *=caracter de separación
# che=Vale 0 o 1
# *=caracter de separación
# $tch=tamaño cache
# != caracter de separación
#
# Y un numero indeterminado de cadenas del tipo siguuenteseparadas por el caracter '$':
# par=Número de particion*cod=Código de partición*sfi=Sistema de ficheros*tam=Tamaño de la partición*ope=Operación
# @= caracter de separación
#____________________________________________________________________
# Captura de parámetros (se ignora el 1er parámetro y se eliminan espacios y tabuladores).
param = ''.join(sys.argv[2:]).replace(' ', '').replace('\t', '')
#param='dis=1*che=0*tch=70000000!par=1*cpt=NTFS*sfi=NTFS*tam=11000000*ope=0%'
#param = ''.join(sys.argv[2:]).replace(' ', '').replace('\t', '')
param = sys.argv[2]
print("param", param)
# Activa navegador para ver progreso
coproc = subprocess.Popen (['/opt/opengnsys/bin/browser', '-qws', 'http://localhost/cgi-bin/httpd-log.sh'])
# Activate browser to see progress
browser_command = ["/opt/opengnsys/bin/browser", "-qws", "http://localhost/cgi-bin/httpd-log.sh"]
coproc = subprocess.Popen(browser_command)
# Read the two blocks of parameters, separated by '!'
tbprm = param.split('!')
# Leer los dos bloques de parámetros, separados por '!'.
tbprm = param.split ('!')
pparam = tbprm[0] # General disk parameters
sparam = tbprm[1] # Partitioning and formatting parameters
# Take disk and cache values, separated by '*'
tbprm = pparam.split('*')
# Toma valores de disco y caché, separados por "*".
# Los valores están en las variables $dis: disco, $che: existe cache (1, 0), $tch: Tamaño de la cache.
tbprm = pparam.split ('*')
dis = ptt = tch = None
for item in tbprm:
if '=' in item:
key, value = item.split('=', 1)
os.environ[key] = value
if '=' not in item: continue
# Error if disk parameter (dis) is not defined
if 'dis' not in os.environ:
sys.exit(int(os.getenv('OG_ERR_FORMAT', 1)))
k, v = item.split ('=', 1)
if k not in ['dis', 'tch', 'ptt']: ## 'ptt' added, unused 'che' removed
print (f'ignoring unknown disk parameter ({k})')
continue
# Take partition distribution values, separated by '%'
cfg = [] # Configuration values
tbp = [] # Partition table
tbf = [] # Formatting table
if 'dis' == k: dis = int (v)
elif 'ptt' == k: ptt = v
elif 'tch' == k: tch = v
# Error si no se define el parámetro de disco (dis).
if dis is None: sys.exit (ogGlobals.OG_ERR_FORMAT)
if ptt is None: ptt = 'MSDOS'
if tch is None: tch = '0'
# Toma valores de distribución de particiones, separados por "%".
tbp = [] # Valores de configuración (parámetros para ogCreatePartitions)
tbf = {} # Tabla de formateo
tbprm = sparam.split('%')
maxp = 0
maxp=0
for item in tbprm:
cfg = item.split('*')
for c in cfg:
if '=' in c:
key, value = c.split('=', 1)
os.environ[key] = value
if os.getenv('cpt') != "CACHE":
tbp.append(f"{os.getenv('cpt')}:{os.getenv('tam')}")
if os.getenv('ope') == '1':
if os.getenv('cpt') not in ["EMPTY", "EXTENDED", "LINUX-LVM", "LVM", "ZPOOL"]:
tbf.append(os.getenv('sfi'))
maxp = max(maxp, int(os.getenv('par', 0)))
if not item: continue ## por si nos pasan un '%' al final de todo
# Leer datos de la partición, separados por "*".
par = cpt = sfi = tam = None
ope = 0
for c in item.split ('*'):
if '=' not in c: continue
# Process
# Current cache size
cache_size = subprocess.check_output(["ogGetCacheSize"]).strip()
k, v = c.split ('=', 1)
if k not in ['par', 'cpt', 'sfi', 'tam', 'ope']:
print (f'ignoring unknown partition parameter ({k})')
continue
# Unmount all partitions and cache
subprocess.run(["ogUnmountAll", os.getenv('dis')], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
subprocess.run(["ogUnmountCache"])
if 'par' == k: par = int (v)
elif 'cpt' == k: cpt = v
elif 'sfi' == k: sfi = v
elif 'tam' == k: tam = v
elif 'ope' == k: ope = int (v)
# Delete partition table if not MSDOS
if subprocess.check_output(["ogGetPartitionTableType", "1"]).strip() != b'MSDOS':
subprocess.run(["ogDeletePartitionTable", os.getenv('dis')])
subprocess.run(["ogExecAndLog", "COMMAND", "ogUpdatePartitionTable", os.getenv('dis')])
subprocess.run(["ogCreatePartitionTable", os.getenv('dis'), "MSDOS"])
missing_params = []
if par is None: missing_params.append ('par')
if cpt is None: missing_params.append ('cpt')
if sfi is None: missing_params.append ('sfi')
if tam is None: missing_params.append ('tam')
if missing_params:
print (f'partition data ({item}) missing required parameters ({' '.join (missing_params)})')
sys.exit (1)
# Initialize cache
if "CACHE" in sparam:
subprocess.run(["ogExecAndLog", "COMMAND", "initCache", os.getenv('tch')])
# Componer datos de particionado.
if 'CACHE' != cpt: tbp.append (f'{cpt}:{tam}')
if ope:
# Si se activa operación de formatear, componer datos de formateo.
if cpt not in ['EMPTY', 'EXTENDED', 'LINUX-LVM', 'LVM', 'ZPOOL']:
tbf[par] = sfi
# Obtener la partición mayor.
if par > maxp: maxp = par
# Define partitioning
subprocess.run(["ogExecAndLog", "COMMAND", "ogCreatePartitions", os.getenv('dis')] + tbp)
if subprocess.run(["ogExecAndLog", "COMMAND", "ogUpdatePartitionTable", os.getenv('dis')]).returncode != 0:
#____________________________________________________
#
# Proceso
#____________________________________________________
# Tamaño actual de la cache
CACHESIZE=CacheLib.ogGetCacheSize()
# Desmonta todas las particiones y la caché
SystemLib.ogEcho (['session', 'log'], None, f'[10] {ogGlobals.lang.MSG_HELP_ogUnmountAll}')
FileSystemLib.ogUnmountAll (dis)
CacheLib.ogUnmountCache()
# Elimina la tabla de particiones
cur_ptt = DiskLib.ogGetPartitionTableType (dis)
if not cur_ptt or ptt != cur_ptt:
DiskLib.ogDeletePartitionTable (dis)
SystemLib.ogExecAndLog ('command', DiskLib.ogUpdatePartitionTable)
# Crea tabla de particiones MSDOS (NOTA: adaptar para tablas GPT).
DiskLib.ogCreatePartitionTable (dis, ptt)
# Inicia la cache.
if 'CACHE' in sparam:
SystemLib.ogEcho (['session', 'log'], None, f'[30] {ogGlobals.lang.MSG_HELP_ogCreateCache}')
SystemLib.ogEcho (['session', 'log'], None, f' initCache {tch}')
SystemLib.ogExecAndLog ('command', CacheLib.initCache, tch)
# Definir particionado.
SystemLib.ogEcho (['session', 'log'], None, f'[50] {ogGlobals.lang.MSG_HELP_ogCreatePartitions}')
SystemLib.ogEcho (['session', 'log'], None, f' ogCreatePartitions {dis} {' '.join (tbp)}')
res = SystemLib.ogExecAndLog ('command', DiskLib.ogCreatePartitions, dis, tbp)
if not res:
coproc.kill()
sys.exit(int(subprocess.check_output(["ogRaiseError", "session", "log", os.getenv('OG_ERR_GENERIC', '1'), f"ogCreatePartitions {os.getenv('dis')} {' '.join(tbp)}"])))
# Format partitions
for par in range(1, maxp + 1):
if tbf[par] == "CACHE":
if cache_size == os.getenv('tch'):
subprocess.run(["ogExecAndLog", "COMMAND", "ogFormatCache"])
elif tbf[par]:
if subprocess.run(["ogExecAndLog", "COMMAND", "ogFormatFs", os.getenv('dis'), str(par), tbf[par]]).returncode != 0:
coproc.kill()
sys.exit(int(subprocess.check_output(["ogRaiseError", "session", "log", os.getenv('OG_ERR_GENERIC', '1'), f"ogFormatFs {os.getenv('dis')} {par} {tbf[par]}"])))
SystemLib.ogRaiseError (['log', 'session'], ogGlobals.OG_ERR_GENERIC, f'ogCreatePartitions {dis} {' '.join (tbp)}')
sys.exit (1)
SystemLib.ogExecAndLog ('command', DiskLib.ogUpdatePartitionTable)
# Formatear particiones
SystemLib.ogEcho (['session', 'log'], None, f'[70] {ogGlobals.lang.MSG_HELP_ogFormat}')
retval = 0
subprocess.run(["ogEcho", "log", "session", f"{os.getenv('MSG_INTERFACE_END')} {retval}"])
for p in range (1, maxp+1):
if p not in tbf: continue
if 'CACHE' == tbf[p]:
if CACHESIZE == tch: # Si el tamaño es distinto ya se ha formateado.
SystemLib.ogEcho (['session', 'log'], None, ' ogFormatCache')
retval = SystemLib.ogExecAndLog ('command', CacheLib.ogFormatCache)
else:
SystemLib.ogEcho (['session', 'log'], None, f' ogFormatFs {dis} {p} {tbf[p]}')
retval = SystemLib.ogExecAndLog ('command', FileSystemLib.ogFormatFs, dis, str(p), tbf[p])
if retval:
coproc.kill()
SystemLib.ogRaiseError (['session', 'log'], ogGlobals.OG_ERR_GENERIC, f'ogFormatFs {dis} {p} {tbf[p]}')
sys.exit (1)
# Registro de fin de ejecución
SystemLib.ogEcho (['session', 'log'], None, f'{ogGlobals.lang.MSG_INTERFACE_END} {retval}')
#___________________________________________________________________
#
# Retorno
#___________________________________________________________________
# Return
coproc.kill()
sys.exit(0)
sys.exit (0)

View File

@ -347,3 +347,15 @@ def ogUnmountCache():
dev = DiskLib.ogDiskToDev (cachepart[0], cachepart[1])
dev = dev.replace ('dev', 'mnt')
if os.path.exists (dev): os.remove (dev)
#/**
# initCache
#@brief Simplemente llama al script initCache
#@brief Es necesario tener una función para poder pasársela a ogExecAndLog
#@param los mismos parametros que initCache
#@return lo mismo que devuelve initCache
#*/ ##
def initCache (*args):
p = subprocess.run (['/opt/opengnsys/images/nati/client/shared/scripts/initCache.py'] + list(args))
return p.returncode