source: client/engine/SystemLib.py @ c2925f1a

ogClonningEnginetest-python-scriptsticket-577ticket-585ticket-693ticket-700
Last change on this file since c2925f1a was c2925f1a, checked in by Antonio Emmanuel Guerrero Silva <aguerrero@…>, 9 months ago

refs #577 Migration library from shell to python3

  • Property mode set to 100644
File size: 9.5 KB
Line 
1import subprocess
2
3def ogEcho(*args):
4    # Variables locales
5    CONT = 1
6    LOGS = ""
7    LOGLEVEL = ""
8    DATETIME = ""
9
10    # Selección de ficheros de registro de incidencias.
11    while CONT:
12        arg = args.pop(0).lower()
13        if arg == "log":
14            LOGS += " " + OGLOGFILE
15        elif arg == "command":
16            LOGS += " " + OGLOGCOMMAND
17        elif arg == "session":
18            LOGS += " " + OGLOGSESSION
19        else:
20            CONT = 0
21
22    # Selección del nivel de registro (opcional).
23    arg = args.pop(0).lower()
24    if arg == "help":
25        pass
26    elif arg == "info" or arg == "warning" or arg == "error":
27        LOGLEVEL = arg
28
29    if LOGLEVEL:
30        DATETIME = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
31        # Registrar mensajes en fichero de log si la depuración no está desactivada.
32        if DEBUG.lower() != "no":
33            LOGS += " " + OGLOGFILE
34        logger.info(f"OpenGnsys {LOGLEVEL} {DATETIME} {' '.join(args)}")
35    else:
36        print(' '.join(args))
37
38def ogExecAndLog(*args):
39    # Variables locales
40    ISCOMMAND = False
41    ISLOG = False
42    ISSESSION = False
43    COMMAND = ""
44    CONTINUE = 1
45    FILES = ""
46    REDIREC = ""
47
48    # Si se solicita, mostrar ayuda.
49    if len(args) > 0 and args[0] == "help":
50        ogHelp(f"{FUNCNAME} str_logfile ... str_command ...",
51                f"{FUNCNAME} COMMAND ls -al /")
52        return
53
54    # Procesar parámetros.
55    while CONTINUE:
56        arg = args.pop(0).lower()
57        if arg == "command":
58            ISCOMMAND = True
59            continue
60        elif arg == "log":
61            ISLOG = True
62            continue
63        elif arg == "session":
64            ISSESSION = True
65            continue
66        else:
67            COMMAND = " ".join(args)
68            CONTINUE = 0
69
70    # Error si no se recibe un comando que ejecutar.
71    if not COMMAND:
72        ogRaiseError(OG_ERR_FORMAT)
73        return
74
75    # Componer lista de ficheros de registro.
76    if ISCOMMAND:
77        FILES = OGLOGCOMMAND
78        open(FILES, "w").close()
79        REDIREC = "2>&1"
80    if ISLOG:
81        FILES += " " + OGLOGFILE
82    if ISSESSION:
83        FILES += " " + OGLOGSESSION
84
85    # Ejecutar comando.
86    subprocess.call(f"{COMMAND} {REDIREC} | tee -a {FILES}", shell=True)
87    # Salida de error del comando ejecutado.
88    return subprocess.PIPESTATUS[0]
89
90def ogGetCaller():
91    # Obtener el nombre del programa o del script que ha llamado al proceso actual.
92    output = subprocess.check_output(["ps", "hp", str(os.getppid()), "-o", "args"]).decode("utf-8")
93    lines = output.split("\n")
94    caller = ""
95    for line in lines:
96        if "bash" in line and line.split()[1] != "":
97            caller = line.split()[1]
98        else:
99            caller = line.split()[0].lstrip("-")
100    return os.path.basename(caller)
101
102def ogHelp(*args):
103    # Variables locales
104    FUNC = ""
105    MSG = ""
106
107    # Mostrar función, descripción y formato.
108    FUNC = args[0] if len(args) > 0 else FUNCNAME[-1]
109    MSG = f"MSG_HELP_{FUNC}"
110    ogEcho("help", f"{MSG_FUNCTION} {FUNC}: {globals()[MSG]}")
111    if len(args) > 1:
112        ogEcho("help", f"    {MSG_FORMAT}: {args[1]}")
113
114    # Mostrar ejemplos (si existen).
115    for example in args[2:]:
116        ogEcho("help", f"    {MSG_EXAMPLE}: {example}")
117
118def ogRaiseError(*args):
119    # Variables locales
120    CONT = 1
121    LOGS = ""
122    MSG = ""
123    CODE = ""
124    FUNCS = ""
125
126    # Si se solicita, mostrar ayuda.
127    if len(args) > 0 and args[0] == "help":
128        ogHelp(f"{FUNCNAME}", f"{FUNCNAME} [str_logfile ...] int_errorcode str_errormessage")
129        return
130
131    # Selección de registros de incidencias.
132    while CONT:
133        arg = args.pop(0).lower()
134        if arg == "log" or arg == "command" or arg == "session":
135            LOGS += " " + arg
136        else:
137            CONT = 0
138
139    # Obtener código y mensaje de error.
140    CODE = args.pop(0)
141    if CODE == OG_ERR_FORMAT:
142        MSG = f"{MSG_ERR_FORMAT} \"{args.pop(0)}\""
143    elif CODE == OG_ERR_NOTFOUND:
144        MSG = f"{MSG_ERR_NOTFOUND} \"{args.pop(0)}\""
145    elif CODE == OG_ERR_OUTOFLIMIT:
146        MSG = f"{MSG_ERR_OUTOFLIMIT} \"{args.pop(0)}\""
147    elif CODE == OG_ERR_PARTITION:
148        MSG = f"{MSG_ERR_PARTITION} \"{args.pop(0)}\""
149    elif CODE == OG_ERR_LOCKED:
150        MSG = f"{MSG_ERR_LOCKED} \"{args.pop(0)}\""
151    elif CODE == OG_ERR_CACHE:
152        MSG = f"{MSG_ERR_CACHE} \"{args.pop(0)}\""
153    elif CODE == OG_ERR_NOGPT:
154        MSG = f"{MSG_ERR_NOGPT} \"{args.pop(0)}\""
155    elif CODE == OG_ERR_REPO:
156        MSG = f"{MSG_ERR_REPO} \"{args.pop(0)}\""
157    elif CODE == OG_ERR_FILESYS:
158        MSG = f"{MSG_ERR_FILESYS} \"{args.pop(0)}\""
159    elif CODE == OG_ERR_IMAGE:
160        MSG = f"{MSG_ERR_IMAGE} \"{args.pop(0)}\""
161    elif CODE == OG_ERR_NOTOS:
162        MSG = f"{MSG_ERR_NOTOS} \"{args.pop(0)}\""
163    elif CODE == OG_ERR_NOTEXEC:
164        MSG = f"{MSG_ERR_NOTEXEC} \"{args.pop(0)}\""
165    elif CODE == OG_ERR_NOTWRITE:
166        MSG = f"{MSG_ERR_NOTWRITE} \"{args.pop(0)}\""
167    elif CODE == OG_ERR_NOTCACHE:
168        MSG = f"{MSG_ERR_NOTCACHE} \"{args.pop(0)}\""
169    elif CODE == OG_ERR_CACHESIZE:
170        MSG = f"{MSG_ERR_CACHESIZE} \"{args.pop(0)}\""
171    elif CODE == OG_ERR_REDUCEFS:
172        MSG = f"{MSG_ERR_REDUCEFS} \"{args.pop(0)}\""
173    elif CODE == OG_ERR_EXTENDFS:
174        MSG = f"{MSG_ERR_EXTENDFS} \"{args.pop(0)}\""
175    elif CODE == OG_ERR_IMGSIZEPARTITION:
176        MSG = f"{MSG_ERR_IMGSIZEPARTITION} \"{args.pop(0)}\""
177    elif CODE == OG_ERR_UPDATECACHE:
178        MSG = f"{MSG_ERR_UPDATECACHE} \"{args.pop(0)}\""
179    elif CODE == OG_ERR_DONTFORMAT:
180        MSG = f"{MSG_ERR_DONTFORMAT} \"{args.pop(0)}\""
181    elif CODE == OG_ERR_IMAGEFILE:
182        MSG = f"{MSG_ERR_IMAGEFILE} \"{args.pop(0)}\""
183    elif CODE == OG_ERR_UCASTSYNTAXT:
184        MSG = f"{MSG_ERR_UCASTSYNTAXT} \"{args.pop(0)}\""
185    elif CODE == OG_ERR_UCASTSENDPARTITION:
186        MSG = f"{MSG_ERR_UCASTSENDPARTITION} \"{args.pop(0)}\""
187    elif CODE == OG_ERR_UCASTSENDFILE:
188        MSG = f"{MSG_ERR_UCASTSENDFILE} \"{args.pop(0)}\""
189    elif CODE == OG_ERR_UCASTRECEIVERPARTITION:
190        MSG = f"{MSG_ERR_UCASTRECEIVERPARTITION} \"{args.pop(0)}\""
191    elif CODE == OG_ERR_UCASTRECEIVERFILE:
192        MSG = f"{MSG_ERR_UCASTRECEIVERFILE} \"{args.pop(0)}\""
193    elif CODE == OG_ERR_MCASTSYNTAXT:
194        MSG = f"{MSG_ERR_MCASTSYNTAXT} \"{args.pop(0)}\""
195    elif CODE == OG_ERR_MCASTSENDFILE:
196        MSG = f"{MSG_ERR_MCASTSENDFILE} \"{args.pop(0)}\""
197    elif CODE == OG_ERR_MCASTRECEIVERFILE:
198        MSG = f"{MSG_ERR_MCASTRECEIVERFILE} \"{args.pop(0)}\""
199    elif CODE == OG_ERR_MCASTSENDPARTITION:
200        MSG = f"{MSG_ERR_MCASTSENDPARTITION} \"{args.pop(0)}\""
201    elif CODE == OG_ERR_MCASTRECEIVERPARTITION:
202        MSG = f"{MSG_ERR_MCASTRECEIVERPARTITION} \"{args.pop(0)}\""
203    elif CODE == OG_ERR_PROTOCOLJOINMASTER:
204        MSG = f"{MSG_ERR_PROTOCOLJOINMASTER} \"{args.pop(0)}\""
205    elif CODE == OG_ERR_DONTMOUNT_IMAGE:
206        MSG = f"{MSG_ERR_DONTMOUNT_IMAGE} \"{args.pop(0)}\""
207    elif CODE == OG_ERR_DONTUNMOUNT_IMAGE:
208        MSG = f"{MSG_ERR_DONTUNMOUNT_IMAGE} \"{args.pop(0)}\""
209    elif CODE == OG_ERR_DONTSYNC_IMAGE:
210        MSG = f"{MSG_ERR_DONTSYNC_IMAGE} \"{args.pop(0)}\""
211    elif CODE == OG_ERR_NOTDIFFERENT:
212        MSG = f"{MSG_ERR_NOTDIFFERENT} \"{args.pop(0)}\""
213    elif CODE == OG_ERR_SYNCHRONIZING:
214        MSG = f"{MSG_ERR_SYNCHRONIZING} \"{args.pop(0)}\""
215    elif CODE == OG_ERR_NOTUEFI:
216        MSG = f"{MSG_ERR_NOTUEFI} \"{args.pop(0)}\""
217    elif CODE == OG_ERR_NOMSDOS:
218        MSG = f"{MSG_ERR_NOMSDOS} \"{args.pop(0)}\""
219    elif CODE == OG_ERR_NOTBIOS:
220        MSG = f"{MSG_ERR_NOTBIOS} \"{args.pop(0)}\""
221    else:
222        MSG = MSG_ERR_GENERIC
223        CODE = OG_ERR_GENERIC
224
225    # Obtener lista de funciones afectadas, incluyendo el script que las llama.
226    FUNCS = " ".join(FUNCNAME[1:])
227    FUNCS = FUNCS.replace("main", os.path.basename(sys.argv[0]))
228
229    # Mostrar mensaje de error si es función depurable y salir con el código indicado.
230    if CODE == OG_ERR_FORMAT or ogCheckStringInGroup(FUNCS, NODEBUGFUNCTIONS) or not ogCheckStringInGroup(FUNCS.split()[0], NODEBUGFUNCTIONS):
231        ogEcho(LOGS, "error", f"{FUNCS.replace(' ', '<-')}: {MSG}", file=sys.stderr)
232
233    return CODE
234
235def ogIsRepoLocked():
236    # Variables locales
237    FILES = ""
238
239    # Si se solicita, mostrar ayuda.
240    if len(sys.argv) > 1 and sys.argv[1] == "help":
241        ogHelp(f"{FUNCNAME}", f"{FUNCNAME}", f"if {FUNCNAME}(): ...")
242
243    # No hacer nada, si no está definido el punto de montaje del repositorio.
244    if not OGIMG:
245        return 1
246
247    # Comprobar si alguno de los ficheros abiertos por los procesos activos está en el
248    # punto de montaje del repositorio de imágenes.
249    FILES = subprocess.check_output(["find", "/proc", "-maxdepth", "2", "-type", "f", "-lname", f"{OGIMG}/*"]).decode("utf-8")
250    return bool(FILES)
251
252def ogCheckProgram(*args):
253    # Si se solicita, mostrar ayuda.
254    if len(args) > 0 and args[0] == "help":
255        ogHelp(f"{FUNCNAME} \"str_program ...\"",
256                f"{FUNCNAME} \"partimage partclone mbuffer\"")
257        return
258
259    # Error si no se recibe 1 parámetro.
260    if len(args) != 1:
261        ogRaiseError(OG_ERR_FORMAT)
262        return
263
264    PERROR = 0
265    PLOG = " "
266    for i in args[0].split():
267        if not shutil.which(i):
268            PERROR = 1
269            PLOG += f" {i}"
270   
271    if PERROR == 1:
272        ogRaiseError(OG_ERR_NOTEXEC, PLOG)
273        return
274    else:
275        return 0
276   
277def ogIsVirtualMachine():
278    output = subprocess.check_output(["dmidecode", "-s", "system-product-name"]).decode("utf-8")
279    if "KVM" in output or "VirtualBox" in output:
280        return 1
281    else:
282        return 0
Note: See TracBrowser for help on using the repository browser.