runtime.py 15 KB

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