From 15a8a462c44e9c839591d753d89be230909eb339 Mon Sep 17 00:00:00 2001 From: ggil Date: Fri, 29 Nov 2024 13:10:05 +0100 Subject: [PATCH] refs #631 - Add journalctl logs to scripts --- bin/createTorrentSum.py | 21 +++++++++++++++++++++ bin/exportImage.py | 9 +++++++++ bin/importImage.py | 12 ++++++++++++ bin/runTorrentSeeder.py | 7 +++++++ bin/runTorrentTracker.py | 8 ++++++++ bin/sendFileMcast.py | 9 +++++++++ bin/sendFileUFTP.py | 5 +++++ bin/updateRepoInfo.py | 10 ++++++++++ bin/updateTrashInfo.py | 7 +++++++ 9 files changed, 88 insertions(+) diff --git a/bin/createTorrentSum.py b/bin/createTorrentSum.py index ed31d99..e3b0094 100644 --- a/bin/createTorrentSum.py +++ b/bin/createTorrentSum.py @@ -32,6 +32,7 @@ import os import sys import subprocess import hashlib +from systemd import journal # -------------------------------------------------------------------------------------------- @@ -139,12 +140,16 @@ def create_torrent(file_path, torrent_file, datafullsum): # Ejecutamos el comando en el sistema, e imprimimos el resultado: try: + journal.send(f"createTorrentSum.py: Running command: {' '.join(splitted_cmd)}", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") result = subprocess.run(splitted_cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + journal.send(f"createTorrentSum.py: Command ReturnCode: {result.returncode}", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") print(f"ReturnCode: {result.returncode}") except subprocess.CalledProcessError as error: + journal.send(f"createTorrentSum.py: Command error: {error}", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api") print(f"ReturnCode: {error.returncode}") print(f"Error Output: {error.stderr.decode()}") except Exception as error: + journal.send(f"createTorrentSum.py: Command exception: {error}", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api") print(f"Se ha producido un error inesperado: {error}") @@ -153,11 +158,14 @@ def update_repo_info(): Como se ve, es necesario que el script se ejecute como sudo, o dará error. """ try: + journal.send("createTorrentSum.py: Running script 'updateRepoInfo.py'...", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") result = subprocess.run(['sudo', 'python3', update_repo_script], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except subprocess.CalledProcessError as error: + journal.send(f"createTorrentSum.py: 'updateRepoInfo.py' error: {error}", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api") print(f"Error Output: {error.stderr.decode()}") sys.exit(3) except Exception as error: + journal.send(f"createTorrentSum.py: 'updateRepoInfo.py' exception: {error}", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api") print(f"Se ha producido un error inesperado: {error}") sys.exit(4) @@ -179,15 +187,18 @@ def main(): # Si no existe el archivo de imagen, imprimimos un mensaje de error y salimos del script: if not os.path.exists(file_path): + journal.send("createTorrentSum.py: Image not found", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api") print("Image file doesn't exist") sys.exit(2) # Si la imagen está bloqueada, imprimimos un mensaje de error y salimos del script: if os.path.exists(f"{file_path}.lock"): + journal.send("createTorrentSum.py: Image is locked", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api") print("Image is locked") sys.exit(3) # Creamos un archivo de bloqueo: + journal.send("createTorrentSum.py: Creating '.lock' file...", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") open(f"{file_path}.lock", "w").close() # Construimos las rutas completas de los archivos ".size", ".sum", ".full.sum" y ".torrent": @@ -198,41 +209,51 @@ def main(): # Creamos el archivo ".size" (pque almacenará el tamaño del archivo), siempre que no exista: if not os.path.exists(size_file): + journal.send("createTorrentSum.py: Creating '.size' file...", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") print("Creating '.size' file...") with open(size_file, 'w') as file: datasize = os.path.getsize(file_path) file.write(str(datasize)) else: + journal.send("createTorrentSum.py: '.size' file exists", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") print("Size file exists") # Creamos el archivo ".sum" (para transferencias Unicast y Multicast), siempre que no exista: if not os.path.exists(sum_file): + journal.send("createTorrentSum.py: Creating '.sum' file...", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") print("Creating '.sum' file...") with open(sum_file, 'w') as file: datasum = get_md5_sum(file_path) file.write(datasum) else: + journal.send("createTorrentSum.py: '.sum' file exists", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") print("Sum file exists") # Creamos el archivo ".full.sum" (para transferencias P2P), siempre que no exista: if not os.path.exists(fullsum_file): + journal.send("createTorrentSum.py: Creating '.full.sum' file...", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") print("Creating '.ful.sum' file...") with open(fullsum_file, 'w') as file: datafullsum = get_md5_fullsum(file_path) file.write(datafullsum) else: + journal.send("createTorrentSum.py: '.full.sum' file exists", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") print("Fullsum file exists") # Creamos el archivo ".torrent" (siempre que no exista): if not os.path.exists(torrent_file): + journal.send("createTorrentSum.py: Creating '.torrent' file...", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") create_torrent(file_path, torrent_file, datafullsum) else: + journal.send("createTorrentSum.py: '.torrent' file exists", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") print("Torrent file exists") # Eliminamos el archivo de bloqueo: + journal.send("createTorrentSum.py: Removing '.lock' file...", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") os.remove(f"{file_path}.lock") # Actualizamos la información del repositorio, ejecutando el script "updateRepoInfo.py": + journal.send("createTorrentSum.py: Updating repository info...", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") print("Updating Repository Info...") update_repo_info() diff --git a/bin/exportImage.py b/bin/exportImage.py index 768a22a..780cee1 100644 --- a/bin/exportImage.py +++ b/bin/exportImage.py @@ -44,6 +44,7 @@ import sys import subprocess import paramiko import warnings +from systemd import journal # -------------------------------------------------------------------------------------------- @@ -121,18 +122,21 @@ def export_image(file_path, remote_host, remote_user): #ssh_client.connect(remote_host, 22, remote_user, 'opengnsys') # Así se haría con password sftp_client = ssh_client.open_sftp() except Exception as error_description: + journal.send(f"exportImage.py: Connection exception: {error_description}", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api") print(f"Connection has returned an exception: {error_description}") sys.exit(4) # Comprobamos si la imagen ya existe en el equipo remoto, en cuyo caso devolvemos un error y salimos del script: try: sftp_client.stat(file_path) + journal.send("exportImage.py: Image already exists on remote repository", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api") print("Image already exists on remote repository.") sys.exit(5) except IOError: print("As expected, image doesn't exist on remote repository.") # Creamos un archivo de bloqueo en el servidor remoto: + journal.send("exportImage.py: Creating '.lock' file...", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") sftp_client.open(f"{file_path}.lock", 'w') # Exportamos la imagen al servidor remoto, junto con sus archivos asociados: @@ -140,12 +144,15 @@ def export_image(file_path, remote_host, remote_user): sftp_client.put(f"{file_path}{ext}", f"{file_path}{ext}") # Renombramos el archivo remoto ".info.checked" a ".info", para que lo pille el script "updateRepoInfo.py": + journal.send("exportImage.py: Renaming '.info.checked' file to '.info'...", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") sftp_client.rename(f"{file_path}.info.checked", f"{file_path}.info") # Eliminamos el archivo de bloqueo del servidor remoto: + journal.send("exportImage.py: Removing '.lock' file...", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") sftp_client.remove(f"{file_path}.lock") # Cerramos el cliente SSH y el cliente SFTP: + journal.send("exportImage.py: Closing remote connection...", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") ssh_client.close() sftp_client.close() @@ -167,11 +174,13 @@ def main(): # Si no existe el archivo de imagen, imprimimos un mensaje de error y salimos del script: if not os.path.exists(file_path): + journal.send("exportImage.py: Image not found", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api") print("Image file doesn't exist") sys.exit(2) # Si la imagen está bloqueada, imprimimos un mensaje de error y salimos del script: if os.path.exists(f"{file_path}.lock"): + journal.send("exportImage.py: Image is locked", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api") print("Image is locked.") sys.exit(3) diff --git a/bin/importImage.py b/bin/importImage.py index 6a7d462..510bde5 100644 --- a/bin/importImage.py +++ b/bin/importImage.py @@ -44,6 +44,7 @@ import sys import subprocess import paramiko import warnings +from systemd import journal # -------------------------------------------------------------------------------------------- @@ -122,6 +123,7 @@ def import_image(file_path, remote_host, remote_user): #ssh_client.connect(remote_host, 22, remote_user, 'opengnsys') # Así se haría con password sftp_client = ssh_client.open_sftp() except Exception as error_description: + journal.send(f"importImage.py: Connection exception: {error_description}", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api") print(f"Connection has returned an exception: {error_description}") sys.exit(2) @@ -129,21 +131,25 @@ def import_image(file_path, remote_host, remote_user): try: sftp_client.stat(file_path) except IOError: + journal.send("importImage.py: Remote image not found", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api") print("Remote image doesn't exist") sys.exit(3) # Comprobamos si la imagen remota está bloqueada, en cuyo caso devolvemos un error y salimos del script, try: # y en caso contrario la importamos (junto con todos sus archivos asociados): sftp_client.stat(f"{file_path}.lock") + journal.send("importImage.py: Remote image is locked", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api") print("Remote image is locked.") sys.exit(4) except IOError: print("Importing remote image...") + journal.send("importImage.py: Creating '.lock' file...", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") open(f"{file_path}.lock", "w").close() # Creamos un archivo de bloqueo for ext in extensions: sftp_client.get(f"{file_path}{ext}", f"{file_path}{ext}") # Cerramos el cliente SSH y el cliente SFTP: + journal.send("importImage.py: Closing remote connection...", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") ssh_client.close() sftp_client.close() @@ -154,11 +160,14 @@ def update_repo_info(): Como se ve, es necesario que el script se ejecute como sudo, o dará error. """ try: + journal.send("importImage.py: Running script 'updateRepoInfo.py'...", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") result = subprocess.run(['sudo', 'python3', update_repo_script], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except subprocess.CalledProcessError as error: + journal.send(f"importImage.py: 'updateRepoInfo.py' error: {error}", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api") print(f"Error Output: {error.stderr.decode()}") sys.exit(2) except Exception as error: + journal.send(f"importImage.py: 'updateRepoInfo.py' exception: {error}", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api") print(f"Se ha producido un error inesperado: {error}") sys.exit(3) @@ -186,12 +195,15 @@ def main(): import_image(file_path, remote_host, remote_user) # Renombramos el archivo ".info.checked" a ".info", para que lo pille el script "updateRepoInfo.py": + journal.send("importImage.py: Renaming '.info' file to '.info.checked'...", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") os.rename(f"{file_path}.info.checked", f"{file_path}.info") # Eliminamos el archivo de bloqueo: + journal.send("importImage.py: Removing '.lock' file...", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") os.remove(f"{file_path}.lock") # Actualizamos la información del repositorio, ejecutando el script "updateRepoInfo.py": + journal.send("importImage.py: Updating repository info...", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") print("Updating Repository Info...") update_repo_info() diff --git a/bin/runTorrentSeeder.py b/bin/runTorrentSeeder.py index 913cc90..1aa2837 100644 --- a/bin/runTorrentSeeder.py +++ b/bin/runTorrentSeeder.py @@ -16,6 +16,7 @@ No recibe ningún parámetro. import os import sys import subprocess +from systemd import journal # -------------------------------------------------------------------------------------------- @@ -37,15 +38,19 @@ def run_bittornado(repo_path): # Creamos una lista con el comando "btlaunchmany.bittornado" y sus parámetros, y lo imprimimos con espacios: splitted_cmd = f"btlaunchmany.bittornado {repo_path}".split() print(f"Sending command: {' '.join(splitted_cmd)}") + journal.send(f"runTorrentSeeder.py: Running command: {' '.join(splitted_cmd)}", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") # Ejecutamos el comando "btlaunchmany.bittornado" en el sistema, e imprimimos el resultado: try: result = subprocess.run(splitted_cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + journal.send(f"runTorrentSeeder.py: Command ReturnCode: {result.returncode}", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") print(f"Bittornado ReturnCode: {result.returncode}") except subprocess.CalledProcessError as error: + journal.send(f"runTorrentSeeder.py: Command error: {error}", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api") print(f"Bittornado ReturnCode: {error.returncode}") print(f"Bittornado Error Output: {error.stderr.decode()}") except Exception as error: + journal.send(f"runTorrentSeeder.py: Command exception: {error}", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api") print(f"Unexpected bittornado error: {error}") @@ -60,8 +65,10 @@ def main(): """ # Finalizamos el proceso "btlaunchmany.bittornado" (en caso de que estuviera corriendo): try: + journal.send("runTorrentSeeder.py: Killing process 'btlaunchmany.bittornado'...", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") subprocess.run(f"pkill btlaunchmany".split(), check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except Exception as error_description: + journal.send("runTorrentSeeder.py: No 'btlaunchmany.bittornado' process running", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") print(f"No btlaunchmany.bittornado process running? Returned error: {error_description}") # Ejecutamos el comando "btlaunchmany.bittornado" (para hacer seed de los torrents): diff --git a/bin/runTorrentTracker.py b/bin/runTorrentTracker.py index 60e2f52..2f278ba 100644 --- a/bin/runTorrentTracker.py +++ b/bin/runTorrentTracker.py @@ -18,6 +18,7 @@ import os import sys import subprocess import time +from systemd import journal # -------------------------------------------------------------------------------------------- @@ -45,15 +46,19 @@ def run_bttrack(repo_path): # Creamos una lista con el comando "bttrack" y sus parámetros, y lo imprimimos con espacios: splitted_cmd = f"bttrack --port {bttrack_port} --dfile {bttrack_dfile} --save_dfile_interval {bttrack_interval} --reannounce_interval {bttrack_interval} --logfile {bttrack_log} --allowed_dir {repo_path} --allow_get {bttrack_allow_get}".split() print(f"Sending command: {' '.join(splitted_cmd)}") + journal.send(f"runTorrentTracker.py: Running command: {' '.join(splitted_cmd)}", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") # Ejecutamos el comando "bttrack" en el sistema, e imprimimos el resultado: try: result = subprocess.run(splitted_cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + journal.send(f"runTorrentTracker.py: Command ReturnCode: {result.returncode}", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") print(f"Bttrack ReturnCode: {result.returncode}") except subprocess.CalledProcessError as error: + journal.send(f"runTorrentTracker.py: Command error: {error}", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api") print(f"Bttrack ReturnCode: {error.returncode}") print(f"Bttrack Error Output: {error.stderr.decode()}") except Exception as error: + journal.send(f"runTorrentTracker.py: Command exception: {error}", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api") print(f"Unexpected bttrack error: {error}") @@ -68,12 +73,15 @@ def main(): """ # Finalizamos el proceso "bttrack" (en caso de que estuviera corriendo): try: + journal.send("runTorrentTracker.py: Killing process 'bttrack'...", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") subprocess.run(f"pkill bttrack".split(), check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except Exception as error_description: + journal.send("runTorrentTracker.py: No 'bttrack' process running", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") print(f"No bttrack process running? Returned error: {error_description}") # Si existe el archivo "/tmp/dstate", lo eliminamos: if os.path.exists(bttrack_dfile): + journal.send("runTorrentTracker.py: Removing '/tmp/dstate'...", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") os.remove(bttrack_dfile) # Esperamos 2 segundos: diff --git a/bin/sendFileMcast.py b/bin/sendFileMcast.py index a5b8222..4153f6d 100644 --- a/bin/sendFileMcast.py +++ b/bin/sendFileMcast.py @@ -31,6 +31,7 @@ sys.argv[2] - Parámetros Multicast (en formato "Port:Duplex:IP:Mpbs:Nclients:Ti import os import sys import subprocess +from systemd import journal # -------------------------------------------------------------------------------------------- @@ -98,13 +99,16 @@ def get_repo_iface(): Como se ve, es necesario que el script se ejecute como sudo, o dará error. """ try: + journal.send("sendFileMcast.py: Running script 'getRepoIface.py'...", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") result = subprocess.run(['sudo', 'python3', repo_iface_script], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) repo_iface = result.stdout.decode().strip() # Es necesario poner "strip", o dará error. return repo_iface except subprocess.CalledProcessError as error: + journal.send(f"sendFileMcast.py: 'getRepoIface.py' error: {error}", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api") print(f"Error Output: {error.stderr.decode()}") sys.exit(3) except Exception as error: + journal.send(f"sendFileMcast.py: 'getRepoIface.py' exception: {error}", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api") print(f"Se ha producido un error inesperado: {error}") sys.exit(4) @@ -141,6 +145,7 @@ def main(): cerror = "8x8/128" # Obtenemos y almacenamos la interfaz del repositorio, mediante el script "getRepoIface.py": + journal.send("sendFileMcast.py: Getting repository interface...", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") repo_iface = get_repo_iface() # Creamos una lista con el comando a enviar (esto es requerido por la función "subprocess.run"). @@ -167,12 +172,16 @@ def main(): # Ejecutamos el comando en el sistema, e imprimimos el resultado: try: + journal.send(f"sendFileMcast.py: Running command: {' '.join(splitted_cmd)}", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") result = subprocess.run(splitted_cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + journal.send(f"sendFileMcast.py: Command ReturnCode: {result.returncode}", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") print(f"ReturnCode: {result.returncode}") except subprocess.CalledProcessError as error: + journal.send(f"sendFileMcast.py: Command error: {error}", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api") print(f"ReturnCode: {error.returncode}") print(f"Error Output: {error.stderr.decode()}") except Exception as error: + journal.send(f"sendFileMcast.py: Command exception: {error}", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api") print(f"Se ha producido un error inesperado: {error}") diff --git a/bin/sendFileUFTP.py b/bin/sendFileUFTP.py index 5ff8c29..ad9316b 100644 --- a/bin/sendFileUFTP.py +++ b/bin/sendFileUFTP.py @@ -36,6 +36,7 @@ sys.argv[2] - Parámetros Multicast/Unicast (en formato "Port:IP:Bitrate") import os import sys import subprocess +from systemd import journal # -------------------------------------------------------------------------------------------- @@ -147,15 +148,19 @@ def main(): splitted_cmd = f"uftp -M {ip} -p {port} -L {log_file} -o -D {cache_path} -Y aes256-cbc -h sha256 -e rsa -c -K 1024 -R {bitrate} {file_path}".split() print(f"Sending command: {' '.join(splitted_cmd)}") + journal.send(f"sendFileUFTP.py: Running command: {' '.join(splitted_cmd)}", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") # Ejecutamos el comando en el sistema, e imprimimos el resultado: try: result = subprocess.run(splitted_cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + journal.send(f"sendFileUFTP.py: Command ReturnCode: {result.returncode}", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") print(f"ReturnCode: {result.returncode}") except subprocess.CalledProcessError as error: + journal.send(f"sendFileUFTP.py: Command error: {error}", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api") print(f"ReturnCode: {error.returncode}") print(f"Error Output: {error.stderr.decode()}") except Exception as error: + journal.send(f"sendFileUFTP.py: Command exception: {error}", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api") print(f"Se ha producido un error inesperado: {error}") diff --git a/bin/updateRepoInfo.py b/bin/updateRepoInfo.py index d11a137..b0e8584 100644 --- a/bin/updateRepoInfo.py +++ b/bin/updateRepoInfo.py @@ -21,6 +21,7 @@ import sys import json import subprocess import shutil +from systemd import journal # -------------------------------------------------------------------------------------------- @@ -177,11 +178,14 @@ def update_trash_info(): Como se ve, es necesario que el script se ejecute como sudo, o dará error. """ try: + journal.send("updateRepoInfo.py: Running script 'updateTrashInfo.py'...", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") result = subprocess.run(['sudo', 'python3', update_trash_script], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except subprocess.CalledProcessError as error: + journal.send(f"updateRepoInfo.py: 'updateTrashInfo.py' error: {error}", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api") print(f"Error Output: {error.stderr.decode()}") sys.exit(3) except Exception as error: + journal.send(f"updateRepoInfo.py: 'updateTrashInfo.py' exception: {error}", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api") print(f"Se ha producido un error inesperado: {error}") sys.exit(4) @@ -198,29 +202,35 @@ def main(): # Comprobamos si tenemos permisos de escritura sobre el directorio que contiene el archivo "repoinfo.json" # ("/opt/opengnsys/etc"), y en caso contrario lanzamos una excepción: if not os.access(os.path.dirname(info_file), os.W_OK): + journal.send(f"updateRepoInfo.py: Cant't access to '{info_file}' directory", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api") raise PermissionError(f"Cannot access {info_file}") # Comprobamos si existe el archivo "repoinfo.json", y en caso contrario lo creamos: if not os.path.exists(info_file): + journal.send("updateRepoInfo.py: Creating empty json file...", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") print("Creating empty json file...") create_empty_json() # Comprobamos si tenemos permisos de escritura sobre el archivo, y en caso contrario lanzamos un error: if not os.access(info_file, os.W_OK): + journal.send(f"updateRepoInfo.py: Cant't write on '{info_file}'", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api") raise PermissionError(f"Cannot access {info_file}") # Llamamos a la función "check_files", para añadir al archivo json las imágenes aun no añadidas # (que son las que tienen asociado un archivo ".info", aun no renombrado o eliminado): + journal.send("updateRepoInfo.py: Checking file images...", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") print("Checking file images...") check_files() # Llamamos a la función "remove_from_json", para eliminar del archivo json las imágenes que fueron eliminadas del repositorio # (solo si el archivo tiene contenido, o dará error): if os.path.getsize(info_file) > 0: + journal.send("updateRepoInfo.py: Removing deleted images from json file...", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") print("Removing deleted images...") remove_from_json() # Actualizamos la información de la papelera, ejecutando el script "updateTrashInfo.py": + journal.send("updateRepoInfo.py: Updating trash info...", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") print("Updating Trash Info...") update_trash_info() diff --git a/bin/updateTrashInfo.py b/bin/updateTrashInfo.py index 6e05c57..c33946c 100644 --- a/bin/updateTrashInfo.py +++ b/bin/updateTrashInfo.py @@ -21,6 +21,7 @@ import grp import json import subprocess import shutil +from systemd import journal # -------------------------------------------------------------------------------------------- @@ -193,31 +194,37 @@ def main(): """ # Comprobamos si existe el directorio correspondiente a la papelera, y en caso contrario lo creamos: if not os.path.exists(trash_path): + journal.send("updateTrashInfo.py: Creting trash folder...", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") print("Creating trash folder...") create_trash_folder() # Comprobamos si tenemos permisos de escritura sobre el directorio que contiene el archivo "trashinfo.json" # ("/opt/opengnsys/etc"), y en caso contrario lanzamos una excepción: if not os.access(os.path.dirname(info_file), os.W_OK): + journal.send(f"updateTrashInfo.py: Cant't access to '{info_file}' directory", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api") raise PermissionError(f"Cannot access {info_file}") # Comprobamos si existe el archivo "trashinfo.json", y en caso contrario lo creamos: if not os.path.exists(info_file): + journal.send("updateTrashInfo.py: Creating empty json file...", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") print("Creating empty json file...") create_empty_json() # Comprobamos si tenemos permisos de escritura sobre el archivo, y en caso contrario lanzamos un error: if not os.access(info_file, os.W_OK): + journal.send(f"updateTrashInfo.py: Cant't write on '{info_file}'", PRIORITY=journal.LOG_ERR, SYSLOG_IDENTIFIER="ogrepo-api") raise PermissionError(f"Cannot access {info_file}") # Llamamos a la función "check_files", para añadir al archivo json las imágenes aun no añadidas # (que son las que tienen asociado un archivo ".info.checked"): + journal.send("updateTrashInfo.py: Checking file images...", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") print("Checking file images...") check_files() # Llamamos a la función "remove_from_json", para eliminar del archivo json las imágenes que ya no están en la papelera # (solo si el archivo tiene contenido, o dará error): if os.path.getsize(info_file) > 0: + journal.send("updateTrashInfo.py: Removing inexistent images from json file...", PRIORITY=journal.LOG_INFO, SYSLOG_IDENTIFIER="ogrepo-api") print("Removing inexistent images...") remove_from_json()