1
0
Fork 0

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 os
import sys import sys
import subprocess import subprocess
import ogGlobals
import SystemLib import SystemLib
import CacheLib
import FileSystemLib
import DiskLib
# Load engine configurator from engine.cfg file. #Load engine configurator from engine.cfg file.
og_engine_configurate = os.getenv('OGENGINECONFIGURATE') #Carga el configurador del engine desde el fichero engine.cfg
if not og_engine_configurate: ## (ogGlobals se encarga)
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}")
# Clear temporary file used as log track by httpdlog # Clear temporary file used as log track by httpdlog
# Limpia los ficheros temporales usados como log de seguimiento para httpdlog # Limpia los ficheros temporales usados como log de seguimiento para httpdlog
og_log_session = os.getenv('OGLOGSESSION') open (ogGlobals.OGLOGSESSION, 'w').close()
og_log_command = os.getenv('OGLOGCOMMAND') 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 # Registro de inicio de ejecución
def SystemLib.ogEcho(log_type, message): SystemLib.ogEcho (['log', 'session'], None, f'{ogGlobals.lang.MSG_INTERFACE_START} {sys.argv}')
# 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:])}")
# Solo ejecutable por OpenGnsys Client. # Solo ejecutable por OpenGnsys Client.
path = os.getenv('PATH') #path = os.getenv('PATH')
if path: #if path:
os.environ['PATH'] = f"{path}:{os.path.dirname(__name__)}" # os.environ['PATH'] = f"{path}:{os.path.dirname(__name__)}"
prog = os.path.basename(__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). # 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 # Leer los dos bloques de parámetros, separados por '!'.
browser_command = ["/opt/opengnsys/bin/browser", "-qws", "http://localhost/cgi-bin/httpd-log.sh"] tbprm = param.split ('!')
coproc = subprocess.Popen(browser_command)
# Read the two blocks of parameters, separated by '!'
tbprm = param.split('!')
pparam = tbprm[0] # General disk parameters pparam = tbprm[0] # General disk parameters
sparam = tbprm[1] # Partitioning and formatting parameters sparam = tbprm[1] # Partitioning and formatting parameters
# Take disk and cache values, separated by '*' # Toma valores de disco y caché, separados por "*".
tbprm = pparam.split('*') # 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: for item in tbprm:
if '=' in item: if '=' not in item: continue
key, value = item.split('=', 1)
os.environ[key] = value
# Error if disk parameter (dis) is not defined k, v = item.split ('=', 1)
if 'dis' not in os.environ: if k not in ['dis', 'tch', 'ptt']: ## 'ptt' added, unused 'che' removed
sys.exit(int(os.getenv('OG_ERR_FORMAT', 1))) print (f'ignoring unknown disk parameter ({k})')
continue
# Take partition distribution values, separated by '%' if 'dis' == k: dis = int (v)
cfg = [] # Configuration values elif 'ptt' == k: ptt = v
tbp = [] # Partition table elif 'tch' == k: tch = v
tbf = [] # Formatting table
# 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('%') tbprm = sparam.split('%')
maxp = 0 maxp=0
for item in tbprm: for item in tbprm:
cfg = item.split('*') if not item: continue ## por si nos pasan un '%' al final de todo
for c in cfg: # Leer datos de la partición, separados por "*".
if '=' in c: par = cpt = sfi = tam = None
key, value = c.split('=', 1) ope = 0
os.environ[key] = value for c in item.split ('*'):
if os.getenv('cpt') != "CACHE": if '=' not in c: continue
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)))
# Process k, v = c.split ('=', 1)
# Current cache size if k not in ['par', 'cpt', 'sfi', 'tam', 'ope']:
cache_size = subprocess.check_output(["ogGetCacheSize"]).strip() print (f'ignoring unknown partition parameter ({k})')
continue
# Unmount all partitions and cache if 'par' == k: par = int (v)
subprocess.run(["ogUnmountAll", os.getenv('dis')], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) elif 'cpt' == k: cpt = v
subprocess.run(["ogUnmountCache"]) elif 'sfi' == k: sfi = v
elif 'tam' == k: tam = v
elif 'ope' == k: ope = int (v)
# Delete partition table if not MSDOS missing_params = []
if subprocess.check_output(["ogGetPartitionTableType", "1"]).strip() != b'MSDOS': if par is None: missing_params.append ('par')
subprocess.run(["ogDeletePartitionTable", os.getenv('dis')]) if cpt is None: missing_params.append ('cpt')
subprocess.run(["ogExecAndLog", "COMMAND", "ogUpdatePartitionTable", os.getenv('dis')]) if sfi is None: missing_params.append ('sfi')
subprocess.run(["ogCreatePartitionTable", os.getenv('dis'), "MSDOS"]) 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 # Componer datos de particionado.
if "CACHE" in sparam: if 'CACHE' != cpt: tbp.append (f'{cpt}:{tam}')
subprocess.run(["ogExecAndLog", "COMMAND", "initCache", os.getenv('tch')]) 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() coproc.kill()
sys.exit(int(subprocess.check_output(["ogRaiseError", "session", "log", os.getenv('OG_ERR_GENERIC', '1'), f"ogCreatePartitions {os.getenv('dis')} {' '.join(tbp)}"]))) SystemLib.ogRaiseError (['log', 'session'], ogGlobals.OG_ERR_GENERIC, f'ogCreatePartitions {dis} {' '.join (tbp)}')
sys.exit (1)
# Format partitions SystemLib.ogExecAndLog ('command', DiskLib.ogUpdatePartitionTable)
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]}"])))
# Formatear particiones
SystemLib.ogEcho (['session', 'log'], None, f'[70] {ogGlobals.lang.MSG_HELP_ogFormat}')
retval = 0 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() coproc.kill()
sys.exit(0) sys.exit (0)

View File

@ -347,3 +347,15 @@ def ogUnmountCache():
dev = DiskLib.ogDiskToDev (cachepart[0], cachepart[1]) dev = DiskLib.ogDiskToDev (cachepart[0], cachepart[1])
dev = dev.replace ('dev', 'mnt') dev = dev.replace ('dev', 'mnt')
if os.path.exists (dev): os.remove (dev) 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