runtime.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. import asyncio
  2. import copy
  3. import os
  4. import tempfile
  5. import uuid
  6. from typing import Any, Optional
  7. from zipfile import ZipFile
  8. import aiohttp
  9. import docker
  10. import tenacity
  11. from opendevin.core.config import AppConfig
  12. from opendevin.core.logger import opendevin_logger as logger
  13. from opendevin.events import EventStream
  14. from opendevin.events.action import (
  15. BrowseInteractiveAction,
  16. BrowseURLAction,
  17. CmdRunAction,
  18. FileReadAction,
  19. FileWriteAction,
  20. IPythonRunCellAction,
  21. )
  22. from opendevin.events.action.action import Action
  23. from opendevin.events.observation import (
  24. ErrorObservation,
  25. NullObservation,
  26. Observation,
  27. )
  28. from opendevin.events.serialization import event_to_dict, observation_from_dict
  29. from opendevin.events.serialization.action import ACTION_TYPE_TO_CLASS
  30. from opendevin.runtime.plugins import PluginRequirement
  31. from opendevin.runtime.runtime import Runtime
  32. from opendevin.runtime.utils import find_available_tcp_port
  33. from opendevin.runtime.utils.runtime_build import build_runtime_image
  34. class EventStreamRuntime(Runtime):
  35. """This runtime will subscribe the event stream.
  36. When receive an event, it will send the event to od-runtime-client which run inside the docker environment.
  37. """
  38. container_name_prefix = 'opendevin-sandbox-'
  39. def __init__(
  40. self,
  41. config: AppConfig,
  42. event_stream: EventStream,
  43. sid: str = 'default',
  44. plugins: list[PluginRequirement] | None = None,
  45. container_image: str | None = None,
  46. ):
  47. self.config = copy.deepcopy(config)
  48. super().__init__(
  49. config, event_stream, sid, plugins
  50. ) # will initialize the event stream
  51. self._port = find_available_tcp_port()
  52. self.api_url = f'http://localhost:{self._port}'
  53. self.session: Optional[aiohttp.ClientSession] = None
  54. self.instance_id = (
  55. sid + str(uuid.uuid4()) if sid is not None else str(uuid.uuid4())
  56. )
  57. # TODO: We can switch to aiodocker when `get_od_sandbox_image` is updated to use aiodocker
  58. self.docker_client: docker.DockerClient = self._init_docker_client()
  59. self.container_image = (
  60. self.config.sandbox.container_image
  61. if container_image is None
  62. else container_image
  63. )
  64. self.container_name = self.container_name_prefix + self.instance_id
  65. self.container = None
  66. self.action_semaphore = asyncio.Semaphore(1) # Ensure one action at a time
  67. async def ainit(self, env_vars: dict[str, str] | None = None):
  68. if self.config.sandbox.od_runtime_extra_deps:
  69. logger.info(
  70. f'Installing extra user-provided dependencies in the runtime image: {self.config.sandbox.od_runtime_extra_deps}'
  71. )
  72. self.container_image = build_runtime_image(
  73. self.container_image,
  74. self.docker_client,
  75. # NOTE: You can need set DEBUG=true to update the source code
  76. # inside the container. This is useful when you want to test/debug the
  77. # latest code in the runtime docker container.
  78. update_source_code=self.config.sandbox.update_source_code,
  79. extra_deps=self.config.sandbox.od_runtime_extra_deps,
  80. )
  81. self.container = await self._init_container(
  82. self.sandbox_workspace_dir,
  83. mount_dir=self.config.workspace_mount_path,
  84. plugins=self.plugins,
  85. )
  86. # MUST call super().ainit() to initialize both default env vars
  87. # AND the ones in env vars!
  88. await super().ainit(env_vars)
  89. logger.info(
  90. f'Container initialized with plugins: {[plugin.name for plugin in self.plugins]}'
  91. )
  92. logger.info(f'Container initialized with env vars: {env_vars}')
  93. @staticmethod
  94. def _init_docker_client() -> docker.DockerClient:
  95. try:
  96. return docker.from_env()
  97. except Exception as ex:
  98. logger.error(
  99. 'Launch docker client failed. Please make sure you have installed docker and started the docker daemon.'
  100. )
  101. raise ex
  102. @tenacity.retry(
  103. stop=tenacity.stop_after_attempt(5),
  104. wait=tenacity.wait_exponential(multiplier=1, min=4, max=60),
  105. )
  106. async def _init_container(
  107. self,
  108. sandbox_workspace_dir: str,
  109. mount_dir: str | None = None,
  110. plugins: list[PluginRequirement] | None = None,
  111. ):
  112. try:
  113. logger.info(
  114. f'Starting container with image: {self.container_image} and name: {self.container_name}'
  115. )
  116. plugin_arg = ''
  117. if plugins is not None and len(plugins) > 0:
  118. plugin_arg = (
  119. f'--plugins {" ".join([plugin.name for plugin in plugins])} '
  120. )
  121. network_mode: str | None = None
  122. port_mapping: dict[str, int] | None = None
  123. if self.config.sandbox.use_host_network:
  124. network_mode = 'host'
  125. logger.warn(
  126. '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'
  127. )
  128. else:
  129. port_mapping = {f'{self._port}/tcp': self._port}
  130. if mount_dir is not None:
  131. volumes = {mount_dir: {'bind': sandbox_workspace_dir, 'mode': 'rw'}}
  132. logger.info(f'Mount dir: {sandbox_workspace_dir}')
  133. else:
  134. logger.warn(
  135. 'Mount dir is not set, will not mount the workspace directory to the container.'
  136. )
  137. volumes = None
  138. logger.info(f'run_as_devin: `{self.config.run_as_devin}`')
  139. if self.config.sandbox.browsergym_eval_env is not None:
  140. browsergym_arg = (
  141. f'--browsergym-eval-env {self.config.sandbox.browsergym_eval_env}'
  142. )
  143. else:
  144. browsergym_arg = ''
  145. container = self.docker_client.containers.run(
  146. self.container_image,
  147. command=(
  148. f'/opendevin/miniforge3/bin/mamba run --no-capture-output -n base '
  149. 'PYTHONUNBUFFERED=1 poetry run '
  150. f'python -u -m opendevin.runtime.client.client {self._port} '
  151. f'--working-dir {sandbox_workspace_dir} '
  152. f'{plugin_arg}'
  153. f'--username {"opendevin" if self.config.run_as_devin else "root"} '
  154. f'--user-id {self.config.sandbox.user_id} '
  155. f'{browsergym_arg}'
  156. ),
  157. network_mode=network_mode,
  158. ports=port_mapping,
  159. working_dir='/opendevin/code/',
  160. name=self.container_name,
  161. detach=True,
  162. environment={'DEBUG': 'true'} if self.config.debug else None,
  163. volumes=volumes,
  164. )
  165. logger.info(f'Container started. Server url: {self.api_url}')
  166. return container
  167. except Exception as e:
  168. logger.error('Failed to start container')
  169. logger.exception(e)
  170. await self.close(close_client=False)
  171. raise e
  172. async def _ensure_session(self):
  173. await asyncio.sleep(1)
  174. if self.session is None or self.session.closed:
  175. self.session = aiohttp.ClientSession()
  176. return self.session
  177. @tenacity.retry(
  178. stop=tenacity.stop_after_attempt(10),
  179. wait=tenacity.wait_exponential(multiplier=2, min=4, max=60),
  180. )
  181. async def _wait_until_alive(self):
  182. logger.info('Reconnecting session')
  183. async with aiohttp.ClientSession() as session:
  184. async with session.get(f'{self.api_url}/alive') as response:
  185. if response.status == 200:
  186. return
  187. else:
  188. msg = f'Action execution API is not alive. Response: {response}'
  189. logger.error(msg)
  190. raise RuntimeError(msg)
  191. @property
  192. def sandbox_workspace_dir(self):
  193. return self.config.workspace_mount_path_in_sandbox
  194. async def close(self, close_client: bool = True):
  195. if self.session is not None and not self.session.closed:
  196. await self.session.close()
  197. containers = self.docker_client.containers.list(all=True)
  198. for container in containers:
  199. try:
  200. if container.name.startswith(self.container_name_prefix):
  201. logs = container.logs(tail=1000).decode('utf-8')
  202. logger.debug(
  203. f'==== Container logs ====\n{logs}\n==== End of container logs ===='
  204. )
  205. container.remove(force=True)
  206. except docker.errors.NotFound:
  207. pass
  208. if close_client:
  209. self.docker_client.close()
  210. async def copy_to(
  211. self, host_src: str, sandbox_dest: str, recursive: bool = False
  212. ) -> dict[str, Any]:
  213. if not os.path.exists(host_src):
  214. raise FileNotFoundError(f'Source file {host_src} does not exist')
  215. session = await self._ensure_session()
  216. await self._wait_until_alive()
  217. try:
  218. if recursive:
  219. # For recursive copy, create a zip file
  220. with tempfile.NamedTemporaryFile(
  221. suffix='.zip', delete=False
  222. ) as temp_zip:
  223. temp_zip_path = temp_zip.name
  224. with ZipFile(temp_zip_path, 'w') as zipf:
  225. for root, _, files in os.walk(host_src):
  226. for file in files:
  227. file_path = os.path.join(root, file)
  228. arcname = os.path.relpath(
  229. file_path, os.path.dirname(host_src)
  230. )
  231. zipf.write(file_path, arcname)
  232. upload_data = {'file': open(temp_zip_path, 'rb')}
  233. else:
  234. # For single file copy
  235. upload_data = {'file': open(host_src, 'rb')}
  236. params = {'destination': sandbox_dest, 'recursive': str(recursive).lower()}
  237. async with session.post(
  238. f'{self.api_url}/upload_file', data=upload_data, params=params
  239. ) as response:
  240. if response.status == 200:
  241. return await response.json()
  242. else:
  243. error_message = await response.text()
  244. raise Exception(f'Copy operation failed: {error_message}')
  245. except asyncio.TimeoutError:
  246. raise TimeoutError('Copy operation timed out')
  247. except Exception as e:
  248. raise RuntimeError(f'Copy operation failed: {str(e)}')
  249. finally:
  250. if recursive:
  251. os.unlink(temp_zip_path)
  252. async def run_action(self, action: Action) -> Observation:
  253. # set timeout to default if not set
  254. if action.timeout is None:
  255. action.timeout = self.config.sandbox.timeout
  256. async with self.action_semaphore:
  257. if not action.runnable:
  258. return NullObservation('')
  259. action_type = action.action # type: ignore[attr-defined]
  260. if action_type not in ACTION_TYPE_TO_CLASS:
  261. return ErrorObservation(f'Action {action_type} does not exist.')
  262. if not hasattr(self, action_type):
  263. return ErrorObservation(
  264. f'Action {action_type} is not supported in the current runtime.'
  265. )
  266. logger.info('Awaiting session')
  267. session = await self._ensure_session()
  268. await self._wait_until_alive()
  269. assert action.timeout is not None
  270. try:
  271. logger.info('Executing command')
  272. async with session.post(
  273. f'{self.api_url}/execute_action',
  274. json={'action': event_to_dict(action)},
  275. timeout=action.timeout,
  276. ) as response:
  277. if response.status == 200:
  278. output = await response.json()
  279. obs = observation_from_dict(output)
  280. obs._cause = action.id # type: ignore[attr-defined]
  281. return obs
  282. else:
  283. error_message = await response.text()
  284. logger.error(f'Error from server: {error_message}')
  285. obs = ErrorObservation(
  286. f'Command execution failed: {error_message}'
  287. )
  288. except asyncio.TimeoutError:
  289. logger.error('No response received within the timeout period.')
  290. obs = ErrorObservation('Command execution timed out')
  291. except Exception as e:
  292. logger.error(f'Error during command execution: {e}')
  293. obs = ErrorObservation(f'Command execution failed: {str(e)}')
  294. return obs
  295. async def run(self, action: CmdRunAction) -> Observation:
  296. return await self.run_action(action)
  297. async def run_ipython(self, action: IPythonRunCellAction) -> Observation:
  298. return await self.run_action(action)
  299. async def read(self, action: FileReadAction) -> Observation:
  300. return await self.run_action(action)
  301. async def write(self, action: FileWriteAction) -> Observation:
  302. return await self.run_action(action)
  303. async def browse(self, action: BrowseURLAction) -> Observation:
  304. return await self.run_action(action)
  305. async def browse_interactive(self, action: BrowseInteractiveAction) -> Observation:
  306. return await self.run_action(action)
  307. ############################################################################
  308. # Keep the same with other runtimes
  309. ############################################################################
  310. def get_working_directory(self):
  311. raise NotImplementedError(
  312. 'This method is not implemented in the runtime client.'
  313. )