source: client/engine/SystemLib.py @ af9a1d9

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

refs #585 Libraries convert to Python3

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