runtime.py 19 KB

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