monitor.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. """Monitoring API router (P4-M3).
  2. Real-time scheduler statistics, queue/running/history endpoints.
  3. """
  4. from fastapi import APIRouter, HTTPException
  5. from typing import Any, Dict, List, Optional
  6. from ..services.batch_scheduler import get_scheduler
  7. router = APIRouter(prefix="/api/monitor", tags=["monitor"])
  8. @router.get("/stats")
  9. async def get_stats() -> Dict[str, Any]:
  10. """Get real-time scheduler statistics."""
  11. scheduler = get_scheduler()
  12. return scheduler.get_statistics()
  13. @router.get("/queue")
  14. async def get_queue(limit: int = 50) -> Dict[str, Any]:
  15. """Get queued tasks list."""
  16. scheduler = get_scheduler()
  17. stats = scheduler.get_statistics()
  18. return {"tasks": stats.get("queued_tasks", [])[:limit], "count": stats.get("queued_count", 0)}
  19. @router.get("/running")
  20. async def get_running() -> Dict[str, Any]:
  21. """Get currently running tasks."""
  22. scheduler = get_scheduler()
  23. stats = scheduler.get_statistics()
  24. return {"tasks": stats.get("running_tasks", []), "count": stats.get("running_count", 0)}
  25. @router.get("/history")
  26. async def get_history(limit: int = 50) -> Dict[str, Any]:
  27. """Get recently completed tasks."""
  28. scheduler = get_scheduler()
  29. stats = scheduler.get_statistics()
  30. return {"tasks": stats.get("recent_completed", [])[-limit:], "count": stats.get("completed_count", 0)}
  31. @router.post("/cancel/{task_id}")
  32. async def cancel_task(task_id: str) -> Dict[str, Any]:
  33. """Cancel a queued or running task."""
  34. scheduler = get_scheduler()
  35. success = scheduler.cancel_task(task_id)
  36. if not success:
  37. raise HTTPException(status_code=404, detail=f"Task {task_id} not found in queue or running")
  38. return {"success": True, "task_id": task_id, "message": "Task cancelled"}
  39. @router.get("/health")
  40. async def health_check() -> Dict[str, Any]:
  41. """System health check."""
  42. import os
  43. import platform
  44. return {
  45. "status": "healthy",
  46. "platform": platform.system(),
  47. "python_version": platform.python_version(),
  48. "scheduler_active": get_scheduler() is not None,
  49. "timestamp": __import__("datetime").datetime.now().isoformat(),
  50. }