81 lines
2.9 KiB
Python
81 lines
2.9 KiB
Python
"""Фоновые задачи: запись в таблицу jobs, параллелизм ограничен MAX_CONCURRENCY."""
|
|||
|
|
import asyncio
|
||
|
|
|
||
|
|
from app.config import get_settings
|
||
|
|
from app.db import session_scope
|
||
|
|
from app.models import Device, Job, now
|
||
|
|
from app.services import ops
|
||
|
|
|
||
|
|
JOB_TYPES = {
|
||
|
|
"backup": ops.run_backup,
|
||
|
|
"ros_update": ops.run_ros_update,
|
||
|
|
"fw_update": ops.run_fw_update,
|
||
|
|
}
|
||
|
|
|
||
|
|
_tasks: set[asyncio.Task] = set()
|
||
|
|
_sem: asyncio.Semaphore | None = None
|
||
|
|
|
||
|
|
|
||
|
|
def _semaphore() -> asyncio.Semaphore:
|
||
|
|
global _sem
|
||
|
|
if _sem is None:
|
||
|
|
_sem = asyncio.Semaphore(get_settings().max_concurrency)
|
||
|
|
return _sem
|
||
|
|
|
||
|
|
|
||
|
|
def _finish(job_id: int, status: str, message: str) -> None:
|
||
|
|
with session_scope() as s:
|
||
|
|
j = s.get(Job, job_id)
|
||
|
|
j.status, j.message = status, message
|
||
|
|
if status in ("done", "failed"):
|
||
|
|
j.finished_at = now()
|
||
|
|
|
||
|
|
|
||
|
|
async def _run(job_id: int, job_type: str, device_id: int) -> None:
|
||
|
|
async with _semaphore():
|
||
|
|
_finish(job_id, "running", "")
|
||
|
|
try:
|
||
|
|
_finish(job_id, "done", await JOB_TYPES[job_type](device_id))
|
||
|
|
except Exception as e: # noqa: BLE001 — любой сбой фиксируем в задаче
|
||
|
|
_finish(job_id, "failed", str(e))
|
||
|
|
|
||
|
|
|
||
|
|
def start_jobs(job_type: str, device_ids: list[int]) -> list[int]:
|
||
|
|
"""Создаёт задачи для списка устройств и запускает их в фоне. Возвращает id задач."""
|
||
|
|
if job_type not in JOB_TYPES:
|
||
|
|
raise ValueError(f"Неизвестный тип задачи: {job_type}")
|
||
|
|
job_ids = []
|
||
|
|
with session_scope() as s:
|
||
|
|
for did in device_ids:
|
||
|
|
d = s.get(Device, did)
|
||
|
|
if d is None:
|
||
|
|
raise LookupError(f"Устройство {did} не найдено")
|
||
|
|
j = Job(device_id=did, device_name=d.name, type=job_type)
|
||
|
|
s.add(j)
|
||
|
|
s.flush()
|
||
|
|
job_ids.append((j.id, did))
|
||
|
|
for jid, did in job_ids:
|
||
|
|
task = asyncio.create_task(_run(jid, job_type, did))
|
||
|
|
_tasks.add(task)
|
||
|
|
task.add_done_callback(_tasks.discard)
|
||
|
|
return [jid for jid, _ in job_ids]
|
||
|
|
|
||
|
|
|
||
|
|
def list_jobs(limit: int = 50) -> list[Job]:
|
||
|
|
with session_scope() as s:
|
||
|
|
return list(s.query(Job).order_by(Job.id.desc()).limit(limit))
|
||
|
|
|
||
|
|
|
||
|
|
def get_job(job_id: int) -> Job:
|
||
|
|
with session_scope() as s:
|
||
|
|
j = s.get(Job, job_id)
|
||
|
|
if j is None:
|
||
|
|
raise LookupError(f"Задача {job_id} не найдена")
|
||
|
|
return j
|
||
|
|
|
||
|
|
|
||
|
|
def fail_stale_jobs() -> None:
|
||
|
|
"""После перезапуска сервера незавершённые задачи помечаются как прерванные."""
|
||
|
|
with session_scope() as s:
|
||
|
|
for j in s.query(Job).filter(Job.status.in_(("pending", "running"))):
|
||
|
|
j.status, j.message, j.finished_at = "failed", "Прервано перезапуском сервера", now()
|