runtime.py 17 KB

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