diff --git a/client/lib/engine/bin/SystemLib.py b/client/lib/engine/bin/SystemLib.py index 13f59bf..1bd755b 100755 --- a/client/lib/engine/bin/SystemLib.py +++ b/client/lib/engine/bin/SystemLib.py @@ -1,9 +1,11 @@ import subprocess import datetime +from zoneinfo import ZoneInfo import sys import os import shutil +import ogGlobals #from engine.DiskLib import * #from engine.CacheLib import * #from engine.StringLib import * @@ -12,41 +14,53 @@ import shutil #OG_ERR_REPO, OG_ERR_NOTOS, OG_ERR_NOGPT, OG_ERR_OUTOFLIMIT, OG_ERR_IMAGE, OG_ERR_CACHE #OGLOGSESSION, OGLOGCOMMAND, OGLOGFILE, OG_ERR_LOCKED, OG_ERR_PARTITION, OG_ERR_FORMAT, OG_ERR_NOTEXEC, OG_ERR_NOTFOUND -def ogEcho(*args): - # Variables locales - CONT = 1 - LOGS = "" - LOGLEVEL = "" - DATETIME = "" +def _logtype2logfile (t): + if 'log' == t: return ogGlobals.OGLOGFILE + elif 'command' == t: return ogGlobals.OGLOGCOMMAND + elif 'session' == t: return ogGlobals.OGLOGSESSION + else: raise Exception (f'unknown log type ({t})') +#/** +# ogEcho [str_logtype ...] [str_loglevel] "str_message" ... +#@brief Muestra mensajes en consola y lo registra en fichero de incidencias. +#@param str_logtype tipo de registro de incidencias ("log", "command", "session") +#@param str_loglevel nivel de registro de incidencias ("info", "warning", "error") +#@param str_message mensaje (puede recibir más de 1 parámetro. +#@return Mensaje mostrado. +#*/ +## zero or more logtypes can be specified +## zero or one loglevel can be specified +## ogEcho ([], None, msg) +## ogEcho ('log', None, msg) +## ogEcho ('session', None, msg) +## ogEcho (['log', 'session'], None, msg) +## ogEcho ([], None, 'info', msg) +## ogEcho ('log', None, 'info', msg) +## ogEcho ('session', None, 'info', msg) +## ogEcho (['log', 'session'], 'info', msg) +def ogEcho (logtypes, loglevel, msg): + logfiles = [] + if type (logtypes) is list: + for l in logtypes: + logfiles.append (_logtype2logfile (l)) + else: ## string + logfiles.append (_logtype2logfile (logtypes)) - # Selección de ficheros de registro de incidencias. - while CONT: - args = list(args) - arg = args.pop(0).lower() - if arg == "log": - LOGS += " " + OGLOGFILE - elif arg == "command": - LOGS += " " + OGLOGCOMMAND - elif arg == "session": - LOGS += " " + OGLOGSESSION - else: - CONT = 0 + if loglevel is None or 'help' == loglevel: + if ogGlobals.DEBUG.lower() != "no": + logfiles.append (ogGlobals.OGLOGFILE) + for f in logfiles: + with open (f, 'a') as fd: + fd.write (msg + '\n') + return - # Selección del nivel de registro (opcional). - arg = args.pop(0).lower() - if arg == "help": - pass - elif arg == "info" or arg == "warning" or arg == "error": - LOGLEVEL = arg + if 'info' == loglevel or 'warning' == loglevel or 'error' == loglevel: + DATETIME = datetime.datetime.now(ZoneInfo(ogGlobals.TZ)).strftime("%F %T %Z") - if LOGLEVEL: - DATETIME = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") - # Registrar mensajes en fichero de log si la depuración no está desactivada. - if DEBUG.lower() != "no": - LOGS += " " + OGLOGFILE - subprocess.call(f"logger -t OpenGnsys {LOGLEVEL} {DATETIME} {' '.join(args)}", shell=True) + for f in logfiles: + with open (f, 'a') as fd: + fd.write (f"OpenGnsys {loglevel} {DATETIME} {msg}\n") else: - print(' '.join(args)) + raise Exception (f'unknown loglevel ({loglevel})') def ogExecAndLog(*args): # Variables locales @@ -130,7 +144,24 @@ def ogGetCaller(): return os.path.basename(caller) -def ogHelp(*args): +import inspect +#/** +# ogHelp ["str_function" ["str_format" ["str_example" ... ]]] +#@brief Muestra mensaje de ayuda para una función determinda. +#@param str_function Nombre de la función. +#@param str_format Formato de ejecución de la función. +#@param str_example Ejemplo de ejecución de la función. +#@return str_help - Salida de ayuda. +#@note Si no se indican parámetros, la función se toma de la variable \c $FUNCNAME +#@note La descripción de la función se toma de la variable compuesta por \c MSG_FUNC_$función incluida en el fichero de idiomas. +#@note Pueden especificarse varios mensajes con ejemplos. +#@version 0.9 - Primera versión para OpenGnSys. +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2009-07-27 +#*/ +def ogHelp (fname, fmt, msg): + func = fname or inspect.stack()[1][3] + MSG = f'MSG_HELP_{func}' # Variables locales FUNC = "" MSG = "" @@ -146,6 +177,23 @@ def ogHelp(*args): # Mostrar ejemplos (si existen). for example in args[2:]: ogEcho("help", f" {MSG_EXAMPLE}: {example}") +#function ogHelp () { +# +## Variables locales. +#local FUNC MSG +# +## Mostrar función, descripción y formato. +#FUNC="${1:-${FUNCNAME[${#FUNCNAME[*]}-1]}}" +#MSG="MSG_HELP_$FUNC" +#ogEcho help "$MSG_FUNCTION $FUNC: ${!MSG}" +#[ -n "$2" ] && ogEcho help " $MSG_FORMAT: $2" +## Mostrar ejemplos (si existen). +#shift 2 +#while [ $# -gt 0 ]; do +# ogEcho help " $MSG_EXAMPLE: $1" +# shift +#done +#} def ogRaiseError(*args): # Variables locales @@ -310,8 +358,5 @@ def ogCheckProgram(*args): return 0 def ogIsVirtualMachine(): - output = subprocess.check_output(["dmidecode", "-s", "system-product-name"]).decode("utf-8") - if "KVM" in output or "VirtualBox" in output: - return 1 - else: - return 0 + output = subprocess.run (["dmidecode", "-s", "system-product-name"], capture_output=True, text=True).stdout + return "KVM" in output or "VirtualBox" in output