|
| 1 | +import signal |
| 2 | +from typing import Optional |
| 3 | + |
| 4 | +from ai.backend.agent.agent import AbstractAgent |
| 5 | +from ai.backend.agent.config.unified import AgentUnifiedConfig |
| 6 | +from ai.backend.agent.monitor import AgentErrorPluginContext, AgentStatsPluginContext |
| 7 | +from ai.backend.agent.types import AgentBackend |
| 8 | +from ai.backend.common.auth import PublicKey |
| 9 | +from ai.backend.common.etcd import AsyncEtcd |
| 10 | +from ai.backend.common.types import aobject |
| 11 | + |
| 12 | + |
| 13 | +class AgentRuntime(aobject): |
| 14 | + local_config: AgentUnifiedConfig |
| 15 | + agent: AbstractAgent |
| 16 | + etcd: AsyncEtcd |
| 17 | + |
| 18 | + _stop_signal: signal.Signals |
| 19 | + |
| 20 | + def __init__( |
| 21 | + self, |
| 22 | + local_config: AgentUnifiedConfig, |
| 23 | + etcd: AsyncEtcd, |
| 24 | + stats_monitor: AgentStatsPluginContext, |
| 25 | + error_monitor: AgentErrorPluginContext, |
| 26 | + agent_public_key: Optional[PublicKey], |
| 27 | + ) -> None: |
| 28 | + self.local_config = local_config |
| 29 | + self.etcd = etcd |
| 30 | + |
| 31 | + self._stop_signal = signal.SIGTERM |
| 32 | + |
| 33 | + self.stats_monitor = stats_monitor |
| 34 | + self.error_monitor = error_monitor |
| 35 | + self.agent_public_key = agent_public_key |
| 36 | + |
| 37 | + async def __ainit__(self) -> None: |
| 38 | + self.agent = await self._create_agent(self.etcd, self.local_config) |
| 39 | + |
| 40 | + async def __aexit__(self, *exc_info) -> None: |
| 41 | + await self.agent.shutdown(self._stop_signal) |
| 42 | + |
| 43 | + def get_agent(self) -> AbstractAgent: |
| 44 | + return self.agent |
| 45 | + |
| 46 | + def get_etcd(self) -> AsyncEtcd: |
| 47 | + return self.etcd |
| 48 | + |
| 49 | + def mark_stop_signal(self, stop_signal: signal.Signals) -> None: |
| 50 | + self._stop_signal = stop_signal |
| 51 | + |
| 52 | + async def _create_agent( |
| 53 | + self, |
| 54 | + etcd: AsyncEtcd, |
| 55 | + agent_config: AgentUnifiedConfig, |
| 56 | + ) -> AbstractAgent: |
| 57 | + agent_kwargs = { |
| 58 | + "stats_monitor": self.stats_monitor, |
| 59 | + "error_monitor": self.error_monitor, |
| 60 | + "agent_public_key": self.agent_public_key, |
| 61 | + } |
| 62 | + |
| 63 | + match self.local_config.agent_common.backend: |
| 64 | + case AgentBackend.DOCKER: |
| 65 | + from .docker.agent import DockerAgent |
| 66 | + |
| 67 | + return await DockerAgent.new(etcd, agent_config, **agent_kwargs) |
| 68 | + case AgentBackend.KUBERNETES: |
| 69 | + from .kubernetes.agent import KubernetesAgent |
| 70 | + |
| 71 | + return await KubernetesAgent.new(etcd, agent_config, **agent_kwargs) |
| 72 | + case AgentBackend.DUMMY: |
| 73 | + from ai.backend.agent.dummy.agent import DummyAgent |
| 74 | + |
| 75 | + return await DummyAgent.new(etcd, agent_config, **agent_kwargs) |
0 commit comments