runtime.py 11 KB

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