source: client/engine/SystemLib.py @ 13ff5a5

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

refs #577 Library bugs resolved for Disk System and FileSystem?

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