runtime.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. import asyncio
  2. import uuid
  3. from typing import Optional
  4. import aiohttp
  5. import docker
  6. import tenacity
  7. from opendevin.core.config import AppConfig
  8. from opendevin.core.logger import opendevin_logger as logger
  9. from opendevin.events import EventSource, EventStream
  10. from opendevin.events.action import (
  11. BrowseInteractiveAction,
  12. BrowseURLAction,
  13. CmdRunAction,
  14. FileReadAction,
  15. FileWriteAction,
  16. IPythonRunCellAction,
  17. )
  18. from opendevin.events.action.action import Action
  19. from opendevin.events.event import Event
  20. from opendevin.events.observation import (
  21. ErrorObservation,
  22. NullObservation,
  23. Observation,
  24. )
  25. from opendevin.events.serialization import event_to_dict, observation_from_dict
  26. from opendevin.events.serialization.action import ACTION_TYPE_TO_CLASS
  27. from opendevin.runtime.plugins import PluginRequirement
  28. from opendevin.runtime.runtime import Runtime
  29. from opendevin.runtime.utils import find_available_tcp_port
  30. from opendevin.runtime.utils.runtime_build import build_runtime_image
  31. class EventStreamRuntime(Runtime):
  32. """This runtime will subscribe the event stream.
  33. When receive an event, it will send the event to od-runtime-client which run inside the docker environment.
  34. """
  35. container_name_prefix = 'opendevin-sandbox-'
  36. def __init__(
  37. self,
  38. config: AppConfig,
  39. event_stream: EventStream,
  40. sid: str = 'default',
  41. container_image: str | None = None,
  42. plugins: list[PluginRequirement] | None = None,
  43. ):
  44. super().__init__(config, event_stream, sid) # will initialize the event stream
  45. self._port = find_available_tcp_port()
  46. self.api_url = f'http://localhost:{self._port}'
  47. self.session: Optional[aiohttp.ClientSession] = None
  48. self.instance_id = (
  49. sid + str(uuid.uuid4()) if sid is not None else str(uuid.uuid4())
  50. )
  51. # TODO: We can switch to aiodocker when `get_od_sandbox_image` is updated to use aiodocker
  52. self.docker_client: docker.DockerClient = self._init_docker_client()
  53. self.container_image = (
  54. self.config.sandbox.container_image
  55. if container_image is None
  56. else container_image
  57. )
  58. self.container_name = self.container_name_prefix + self.instance_id
  59. self.plugins = plugins if plugins is not None else []
  60. self.container = None
  61. self.action_semaphore = asyncio.Semaphore(1) # Ensure one action at a time
  62. async def ainit(self, env_vars: dict[str, str] | None = None):
  63. self.container_image = build_runtime_image(
  64. self.container_image,
  65. self.docker_client,
  66. # NOTE: You can need set DEBUG=true to update the source code
  67. # inside the container. This is useful when you want to test/debug the
  68. # latest code in the runtime docker container.
  69. update_source_code=self.config.sandbox.update_source_code,
  70. )
  71. self.container = await self._init_container(
  72. self.sandbox_workspace_dir,
  73. mount_dir=self.config.workspace_mount_path,
  74. plugins=self.plugins,
  75. )
  76. # MUST call super().ainit() to initialize both default env vars
  77. # AND the ones in env vars!
  78. await super().ainit(env_vars)
  79. @staticmethod
  80. def _init_docker_client() -> docker.DockerClient:
  81. try:
  82. return docker.from_env()
  83. except Exception as ex:
  84. logger.error(
  85. 'Launch docker client failed. Please make sure you have installed docker and started the docker daemon.'
  86. )
  87. raise ex
  88. @tenacity.retry(
  89. stop=tenacity.stop_after_attempt(5),
  90. wait=tenacity.wait_exponential(multiplier=1, min=4, max=60),
  91. )
  92. async def _init_container(
  93. self,
  94. sandbox_workspace_dir: str,
  95. mount_dir: str | None = None,
  96. plugins: list[PluginRequirement] | None = None,
  97. ):
  98. try:
  99. logger.info(
  100. f'Starting container with image: {self.container_image} and name: {self.container_name}'
  101. )
  102. if plugins is None:
  103. plugins = []
  104. plugin_names = ' '.join([plugin.name for plugin in plugins])
  105. network_mode: str | None = None
  106. port_mapping: dict[str, int] | None = None
  107. if self.config.sandbox.use_host_network:
  108. network_mode = 'host'
  109. logger.warn(
  110. 'Using host network mode. If you are using MacOS, please make sure you have the latest version of Docker Desktop and enabled host network feature: https://docs.docker.com/network/drivers/host/#docker-desktop'
  111. )
  112. else:
  113. port_mapping = {f'{self._port}/tcp': self._port}
  114. if mount_dir is not None:
  115. volumes = {mount_dir: {'bind': sandbox_workspace_dir, 'mode': 'rw'}}
  116. else:
  117. logger.warn(
  118. 'Mount dir is not set, will not mount the workspace directory to the container.'
  119. )
  120. volumes = None
  121. container = self.docker_client.containers.run(
  122. self.container_image,
  123. command=(
  124. f'/opendevin/miniforge3/bin/mamba run --no-capture-output -n base '
  125. 'PYTHONUNBUFFERED=1 poetry run '
  126. f'python -u -m opendevin.runtime.client.client {self._port} '
  127. f'--working-dir {sandbox_workspace_dir} '
  128. f'--plugins {plugin_names}'
  129. ),
  130. network_mode=network_mode,
  131. ports=port_mapping,
  132. working_dir='/opendevin/code/',
  133. name=self.container_name,
  134. detach=True,
  135. environment={'DEBUG': 'true'} if self.config.debug else None,
  136. volumes=volumes,
  137. )
  138. logger.info(f'Container started. Server url: {self.api_url}')
  139. return container
  140. except Exception as e:
  141. logger.error('Failed to start container')
  142. logger.exception(e)
  143. await self.close(close_client=False)
  144. raise e
  145. async def _ensure_session(self):
  146. if self.session is None or self.session.closed:
  147. self.session = aiohttp.ClientSession()
  148. return self.session
  149. @tenacity.retry(
  150. stop=tenacity.stop_after_attempt(10),
  151. wait=tenacity.wait_exponential(multiplier=2, min=4, max=600),
  152. )
  153. async def _wait_until_alive(self):
  154. async with aiohttp.ClientSession() as session:
  155. async with session.get(f'{self.api_url}/alive') as response:
  156. if response.status == 200:
  157. return
  158. else:
  159. logger.error(
  160. f'Action execution API is not alive. Response: {response}'
  161. )
  162. raise RuntimeError(
  163. f'Action execution API is not alive. Response: {response}'
  164. )
  165. @property
  166. def sandbox_workspace_dir(self):
  167. return self.config.workspace_mount_path_in_sandbox
  168. async def close(self, close_client: bool = True):
  169. if self.session is not None and not self.session.closed:
  170. await self.session.close()
  171. containers = self.docker_client.containers.list(all=True)
  172. for container in containers:
  173. try:
  174. if container.name.startswith(self.container_name_prefix):
  175. logs = container.logs(tail=1000).decode('utf-8')
  176. logger.debug(
  177. f'==== Container logs ====\n{logs}\n==== End of container logs ===='
  178. )
  179. container.remove(force=True)
  180. except docker.errors.NotFound:
  181. pass
  182. if close_client:
  183. self.docker_client.close()
  184. async def on_event(self, event: Event) -> None:
  185. logger.info(f'EventStreamRuntime: on_event triggered: {event}')
  186. if isinstance(event, Action):
  187. logger.info(event, extra={'msg_type': 'ACTION'})
  188. observation = await self.run_action(event)
  189. # observation._cause = event.id # type: ignore[attr-defined]
  190. logger.info(observation, extra={'msg_type': 'OBSERVATION'})
  191. source = event.source if event.source else EventSource.AGENT
  192. await self.event_stream.add_event(observation, source)
  193. async def run_action(self, action: Action, timeout: int = 600) -> Observation:
  194. async with self.action_semaphore:
  195. if not action.runnable:
  196. return NullObservation('')
  197. action_type = action.action # type: ignore[attr-defined]
  198. if action_type not in ACTION_TYPE_TO_CLASS:
  199. return ErrorObservation(f'Action {action_type} does not exist.')
  200. if not hasattr(self, action_type):
  201. return ErrorObservation(
  202. f'Action {action_type} is not supported in the current runtime.'
  203. )
  204. session = await self._ensure_session()
  205. await self._wait_until_alive()
  206. try:
  207. async with session.post(
  208. f'{self.api_url}/execute_action',
  209. json={'action': event_to_dict(action)},
  210. timeout=timeout,
  211. ) as response:
  212. if response.status == 200:
  213. output = await response.json()
  214. obs = observation_from_dict(output)
  215. obs._cause = action.id # type: ignore[attr-defined]
  216. return obs
  217. else:
  218. error_message = await response.text()
  219. logger.error(f'Error from server: {error_message}')
  220. obs = ErrorObservation(
  221. f'Command execution failed: {error_message}'
  222. )
  223. except asyncio.TimeoutError:
  224. logger.error('No response received within the timeout period.')
  225. obs = ErrorObservation('Command execution timed out')
  226. except Exception as e:
  227. logger.error(f'Error during command execution: {e}')
  228. obs = ErrorObservation(f'Command execution failed: {str(e)}')
  229. obs._parent = action.id # type: ignore[attr-defined]
  230. return obs
  231. async def run(self, action: CmdRunAction) -> Observation:
  232. return await self.run_action(action)
  233. async def run_ipython(self, action: IPythonRunCellAction) -> Observation:
  234. return await self.run_action(action)
  235. async def read(self, action: FileReadAction) -> Observation:
  236. return await self.run_action(action)
  237. async def write(self, action: FileWriteAction) -> Observation:
  238. return await self.run_action(action)
  239. async def browse(self, action: BrowseURLAction) -> Observation:
  240. return await self.run_action(action)
  241. async def browse_interactive(self, action: BrowseInteractiveAction) -> Observation:
  242. return await self.run_action(action)
  243. ############################################################################
  244. # Keep the same with other runtimes
  245. ############################################################################
  246. def get_working_directory(self):
  247. raise NotImplementedError(
  248. 'This method is not implemented in the runtime client.'
  249. )
  250. ############################################################################
  251. # Initialization work inside sandbox image
  252. ############################################################################
  253. # init_runtime_tools direcctly do as what Runtime do
  254. # Do in the od_runtime_client
  255. # Overwrite the init_sandbox_plugins
  256. def init_sandbox_plugins(self, plugins: list[PluginRequirement]) -> None:
  257. pass