worker.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. from __future__ import annotations
  2. import os
  3. import socket
  4. import time
  5. import traceback
  6. from dataclasses import dataclass
  7. from math import ceil
  8. from uuid import uuid4
  9. from core_shared import try_build_redis_client
  10. from core_shared.task_queue import RUNTIME_NODE_RUN_QUEUE, build_task_queue_consumer
  11. from sqlalchemy.orm import Session, sessionmaker
  12. from app.application.services import build_runtime_application_service
  13. from app.bootstrap.settings import RuntimeServiceSettings
  14. from app.db.session import build_session_factory
  15. @dataclass(frozen=True)
  16. class RuntimeWorkerStats:
  17. worker_key: str
  18. executed_count: int = 0
  19. idle_count: int = 0
  20. error_count: int = 0
  21. class RuntimeWorker:
  22. def __init__(
  23. self,
  24. *,
  25. settings: RuntimeServiceSettings,
  26. session_factory: sessionmaker[Session],
  27. worker_key: str) -> None:
  28. self.settings = settings
  29. self.session_factory = session_factory
  30. self.worker_key = worker_key
  31. self.redis_client = try_build_redis_client(settings.redis_url)
  32. self.task_queue = build_task_queue_consumer(
  33. client=self.redis_client,
  34. queue_name=RUNTIME_NODE_RUN_QUEUE)
  35. def run_forever(self) -> RuntimeWorkerStats:
  36. executed_count = 0
  37. idle_count = 0
  38. error_count = 0
  39. while True:
  40. try:
  41. executed = self.run_once()
  42. except Exception:
  43. error_count += 1
  44. traceback.print_exc()
  45. executed = False
  46. if executed:
  47. executed_count += 1
  48. idle_count = 0
  49. else:
  50. idle_count += 1
  51. if self.task_queue is None:
  52. time.sleep(self.settings.worker_poll_interval_seconds)
  53. if self.settings.worker_max_idle_cycles is not None:
  54. if idle_count >= self.settings.worker_max_idle_cycles:
  55. return RuntimeWorkerStats(
  56. worker_key=self.worker_key,
  57. executed_count=executed_count,
  58. idle_count=idle_count,
  59. error_count=error_count)
  60. def run_once(self) -> bool:
  61. self._wait_for_queue_signal()
  62. db = self.session_factory()
  63. try:
  64. service = build_runtime_application_service(db=db, settings=self.settings)
  65. result = service.execute_next_claimed_node_run(
  66. worker_key=self.worker_key,
  67. lease_seconds=self.settings.worker_lease_seconds,
  68. redis_client=self.redis_client)
  69. return result is not None
  70. finally:
  71. db.close()
  72. def _wait_for_queue_signal(self) -> None:
  73. if self.task_queue is None:
  74. return
  75. try:
  76. self.task_queue.dequeue(
  77. timeout_seconds=max(1, ceil(self.settings.worker_poll_interval_seconds)))
  78. except Exception:
  79. return
  80. def build_worker_key() -> str:
  81. configured_key = os.getenv("AGENT_PLATFORM_WORKER_KEY")
  82. if configured_key:
  83. return configured_key
  84. hostname = socket.gethostname()
  85. return f"{hostname}-{uuid4().hex[:8]}"
  86. def main() -> None:
  87. settings = RuntimeServiceSettings()
  88. worker = RuntimeWorker(
  89. settings=settings,
  90. session_factory=build_session_factory(settings),
  91. worker_key=build_worker_key())
  92. stats = worker.run_forever()
  93. print(
  94. "runtime-worker stopped "
  95. f"worker_key={stats.worker_key} "
  96. f"executed_count={stats.executed_count} "
  97. f"idle_count={stats.idle_count} "
  98. f"error_count={stats.error_count}",
  99. flush=True)
  100. if __name__ == "__main__":
  101. main()