runtime.py 15 KB

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