add comment

This commit is contained in:
2025-07-11 22:06:45 +02:00
parent 0022d0e326
commit b1ce9061b1
8 changed files with 212 additions and 591 deletions

View File

@@ -6,7 +6,6 @@ import asyncio
import os
import aiomysql
import contextvars
import subprocess
# Import custom modules for configuration and database connection
@@ -21,7 +20,16 @@ worker_context = contextvars.ContextVar('worker_id', default='00')
# Formatter personalizzato che include il worker_id
class WorkerFormatter(logging.Formatter):
"""Formatter personalizzato che include l'ID del worker nei log."""
def format(self, record):
"""Formatta il record di log includendo l'ID del worker.
Args:
record: Il record di log da formattare.
Returns:
La stringa formattata del record di log.
"""
record.worker_id = worker_context.get()
return super().format(record)
@@ -34,6 +42,17 @@ ELAB_PROCESSING_DELAY = 0.2
NO_RECORD_SLEEP = 60
async def worker(worker_id: int, cfg: object, pool) -> None:
"""Esegue il ciclo di lavoro per l'elaborazione dei dati caricati.
Il worker preleva un record dal database che indica dati pronti per
l'elaborazione, esegue un comando Matlab associato e attende
prima di iniziare un nuovo ciclo.
Args:
worker_id (int): L'ID univoco del worker.
cfg (object): L'oggetto di configurazione.
pool: Il pool di connessioni al database.
"""
# Imposta il context per questo worker
worker_context.set(f"W{worker_id}")
@@ -54,14 +73,19 @@ async def worker(worker_id: int, cfg: object, pool) -> None:
# matlab_error_filename = f'{cfg.matlab_error_path}{unit_name}{tool_name}_output_error.txt'
success = await subprocess.run(matlab_cmd,
cwd=cfg.matlab_func_path,
capture_output=True,
text=True,
check=True)
proc = await asyncio.create_subprocess_shell(
matlab_cmd,
cwd=cfg.matlab_func_path,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
if not success:
stdout, stderr = await proc.communicate()
if proc.returncode != 0:
logger.error("Errore durante l'elaborazione")
logger.error(stderr.decode().strip())
logger.info(stdout.decode().strip())
await asyncio.sleep(ELAB_PROCESSING_DELAY)
else:
logger.info("Nessun record disponibile")
@@ -73,7 +97,15 @@ async def worker(worker_id: int, cfg: object, pool) -> None:
async def main():
"""Main function: avvia i worker e gestisce il ciclo principale."""
"""Funzione principale che inizializza e avvia il sistema di elaborazione.
Questa funzione si occupa di:
- Caricare la configurazione.
- Impostare il logging.
- Creare un pool di connessioni al database.
- Avviare i worker concorrenti per l'elaborazione.
- Gestire l'arresto controllato del sistema.
"""
logger.info("Avvio del sistema...")
cfg = setting.Config()
@@ -106,7 +138,7 @@ async def main():
user=cfg.dbuser,
password=cfg.dbpass,
db=cfg.dbname,
minsize=4,
minsize=cfg.max_threads,
maxsize=cfg.max_threads*4,
pool_recycle=3600
)