eventstream_runtime.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. import os
  2. import tempfile
  3. import threading
  4. from functools import lru_cache
  5. from typing import Callable
  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 DEBUG
  12. from openhands.core.logger import openhands_logger as logger
  13. from openhands.events import EventStream
  14. from openhands.events.action import (
  15. ActionConfirmationStatus,
  16. BrowseInteractiveAction,
  17. BrowseURLAction,
  18. CmdRunAction,
  19. FileEditAction,
  20. FileReadAction,
  21. FileWriteAction,
  22. IPythonRunCellAction,
  23. )
  24. from openhands.events.action.action import Action
  25. from openhands.events.observation import (
  26. FatalErrorObservation,
  27. NullObservation,
  28. Observation,
  29. UserRejectObservation,
  30. )
  31. from openhands.events.serialization import event_to_dict, observation_from_dict
  32. from openhands.events.serialization.action import ACTION_TYPE_TO_CLASS
  33. from openhands.runtime.base import Runtime
  34. from openhands.runtime.builder import DockerRuntimeBuilder
  35. from openhands.runtime.plugins import PluginRequirement
  36. from openhands.runtime.utils import find_available_tcp_port
  37. from openhands.runtime.utils.request import send_request_with_retry
  38. from openhands.runtime.utils.runtime_build import build_runtime_image
  39. from openhands.utils.tenacity_stop import stop_if_should_exit
  40. class LogBuffer:
  41. """Synchronous buffer for Docker container logs.
  42. This class provides a thread-safe way to collect, store, and retrieve logs
  43. from a Docker container. It uses a list to store log lines and provides methods
  44. for appending, retrieving, and clearing logs.
  45. """
  46. def __init__(self, container: docker.models.containers.Container):
  47. self.client_ready = False
  48. self.init_msg = 'Runtime client initialized.'
  49. self.buffer: list[str] = []
  50. self.lock = threading.Lock()
  51. self._stop_event = threading.Event()
  52. self.log_generator = container.logs(stream=True, follow=True)
  53. self.log_stream_thread = threading.Thread(target=self.stream_logs)
  54. self.log_stream_thread.daemon = True
  55. self.log_stream_thread.start()
  56. def append(self, log_line: str):
  57. with self.lock:
  58. self.buffer.append(log_line)
  59. def get_and_clear(self) -> list[str]:
  60. with self.lock:
  61. logs = list(self.buffer)
  62. self.buffer.clear()
  63. return logs
  64. def stream_logs(self):
  65. """Stream logs from the Docker container in a separate thread.
  66. This method runs in its own thread to handle the blocking
  67. operation of reading log lines from the Docker SDK's synchronous generator.
  68. """
  69. try:
  70. for log_line in self.log_generator:
  71. if self._stop_event.is_set():
  72. break
  73. if log_line:
  74. decoded_line = log_line.decode('utf-8').rstrip()
  75. self.append(decoded_line)
  76. if self.init_msg in decoded_line:
  77. self.client_ready = True
  78. except Exception as e:
  79. logger.error(f'Error streaming docker logs: {e}')
  80. def __del__(self):
  81. if self.log_stream_thread.is_alive():
  82. logger.warn(
  83. "LogBuffer was not properly closed. Use 'log_buffer.close()' for clean shutdown."
  84. )
  85. self.close(timeout=5)
  86. def close(self, timeout: float = 5.0):
  87. self._stop_event.set()
  88. self.log_stream_thread.join(timeout)
  89. class EventStreamRuntime(Runtime):
  90. """This runtime will subscribe the event stream.
  91. When receive an event, it will send the event to runtime-client which run inside the docker environment.
  92. Args:
  93. config (AppConfig): The application configuration.
  94. event_stream (EventStream): The event stream to subscribe to.
  95. sid (str, optional): The session ID. Defaults to 'default'.
  96. plugins (list[PluginRequirement] | None, optional): List of plugin requirements. Defaults to None.
  97. env_vars (dict[str, str] | None, optional): Environment variables to set. Defaults to None.
  98. """
  99. container_name_prefix = 'openhands-runtime-'
  100. # Need to provide this method to allow inheritors to init the Runtime
  101. # without initting the EventStreamRuntime.
  102. def init_base_runtime(
  103. self,
  104. config: AppConfig,
  105. event_stream: EventStream,
  106. sid: str = 'default',
  107. plugins: list[PluginRequirement] | None = None,
  108. env_vars: dict[str, str] | None = None,
  109. status_message_callback: Callable | None = None,
  110. attach_to_existing: bool = False,
  111. ):
  112. super().__init__(
  113. config,
  114. event_stream,
  115. sid,
  116. plugins,
  117. env_vars,
  118. status_message_callback,
  119. attach_to_existing,
  120. )
  121. def __init__(
  122. self,
  123. config: AppConfig,
  124. event_stream: EventStream,
  125. sid: str = 'default',
  126. plugins: list[PluginRequirement] | None = None,
  127. env_vars: dict[str, str] | None = None,
  128. status_message_callback: Callable | None = None,
  129. attach_to_existing: bool = False,
  130. ):
  131. self.config = config
  132. self._host_port = 30000 # initial dummy value
  133. self._container_port = 30001 # initial dummy value
  134. self.api_url = f'{self.config.sandbox.local_runtime_url}:{self._container_port}'
  135. self.session = requests.Session()
  136. self.status_message_callback = status_message_callback
  137. self.docker_client: docker.DockerClient = self._init_docker_client()
  138. self.base_container_image = self.config.sandbox.base_container_image
  139. self.runtime_container_image = self.config.sandbox.runtime_container_image
  140. self.container_name = self.container_name_prefix + sid
  141. self.container = None
  142. self.action_semaphore = threading.Semaphore(1) # Ensure one action at a time
  143. self.runtime_builder = DockerRuntimeBuilder(self.docker_client)
  144. # Buffer for container logs
  145. self.log_buffer: LogBuffer | None = None
  146. if self.config.sandbox.runtime_extra_deps:
  147. logger.debug(
  148. f'Installing extra user-provided dependencies in the runtime image: {self.config.sandbox.runtime_extra_deps}'
  149. )
  150. self.skip_container_logs = (
  151. os.environ.get('SKIP_CONTAINER_LOGS', 'false').lower() == 'true'
  152. )
  153. self.init_base_runtime(
  154. config,
  155. event_stream,
  156. sid,
  157. plugins,
  158. env_vars,
  159. status_message_callback,
  160. attach_to_existing,
  161. )
  162. async def connect(self):
  163. self.send_status_message('STATUS$STARTING_RUNTIME')
  164. if not self.attach_to_existing:
  165. if self.runtime_container_image is None:
  166. if self.base_container_image is None:
  167. raise ValueError(
  168. 'Neither runtime container image nor base container image is set'
  169. )
  170. logger.info('Preparing container, this might take a few minutes...')
  171. self.send_status_message('STATUS$STARTING_CONTAINER')
  172. self.runtime_container_image = build_runtime_image(
  173. self.base_container_image,
  174. self.runtime_builder,
  175. platform=self.config.sandbox.platform,
  176. extra_deps=self.config.sandbox.runtime_extra_deps,
  177. force_rebuild=self.config.sandbox.force_rebuild_runtime,
  178. )
  179. self._init_container(
  180. sandbox_workspace_dir=self.config.workspace_mount_path_in_sandbox, # e.g. /workspace
  181. mount_dir=self.config.workspace_mount_path, # e.g. /opt/openhands/_test_workspace
  182. plugins=self.plugins,
  183. )
  184. else:
  185. self._attach_to_container()
  186. logger.info('Waiting for client to become ready...')
  187. self.send_status_message('STATUS$WAITING_FOR_CLIENT')
  188. self._wait_until_alive()
  189. if not self.attach_to_existing:
  190. self.setup_initial_env()
  191. logger.info(
  192. f'Container initialized with plugins: {[plugin.name for plugin in self.plugins]}'
  193. )
  194. self.send_status_message(' ')
  195. @staticmethod
  196. @lru_cache(maxsize=1)
  197. def _init_docker_client() -> docker.DockerClient:
  198. try:
  199. return docker.from_env()
  200. except Exception as ex:
  201. logger.error(
  202. 'Launch docker client failed. Please make sure you have installed docker and started docker desktop/daemon.'
  203. )
  204. raise ex
  205. @tenacity.retry(
  206. stop=tenacity.stop_after_attempt(5) | stop_if_should_exit(),
  207. wait=tenacity.wait_exponential(multiplier=1, min=4, max=60),
  208. )
  209. def _init_container(
  210. self,
  211. sandbox_workspace_dir: str,
  212. mount_dir: str | None = None,
  213. plugins: list[PluginRequirement] | None = None,
  214. ):
  215. try:
  216. logger.info('Preparing to start container...')
  217. self.send_status_message('STATUS$PREPARING_CONTAINER')
  218. plugin_arg = ''
  219. if plugins is not None and len(plugins) > 0:
  220. plugin_arg = (
  221. f'--plugins {" ".join([plugin.name for plugin in plugins])} '
  222. )
  223. self._host_port = self._find_available_port()
  224. self._container_port = (
  225. self._host_port
  226. ) # in future this might differ from host port
  227. self.api_url = (
  228. f'{self.config.sandbox.local_runtime_url}:{self._container_port}'
  229. )
  230. use_host_network = self.config.sandbox.use_host_network
  231. network_mode: str | None = 'host' if use_host_network else None
  232. port_mapping: dict[str, list[dict[str, str]]] | None = (
  233. None
  234. if use_host_network
  235. else {
  236. f'{self._container_port}/tcp': [{'HostPort': str(self._host_port)}]
  237. }
  238. )
  239. if use_host_network:
  240. logger.warn(
  241. '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'
  242. )
  243. # Combine environment variables
  244. environment = {
  245. 'port': str(self._container_port),
  246. 'PYTHONUNBUFFERED': 1,
  247. }
  248. if self.config.debug or DEBUG:
  249. environment['DEBUG'] = 'true'
  250. logger.debug(f'Workspace Base: {self.config.workspace_base}')
  251. if mount_dir is not None and sandbox_workspace_dir is not None:
  252. # e.g. result would be: {"/home/user/openhands/workspace": {'bind': "/workspace", 'mode': 'rw'}}
  253. volumes = {mount_dir: {'bind': sandbox_workspace_dir, 'mode': 'rw'}}
  254. logger.debug(f'Mount dir: {mount_dir}')
  255. else:
  256. logger.warn(
  257. 'Warning: Mount dir is not set, will not mount the workspace directory to the container!\n'
  258. )
  259. volumes = None
  260. logger.debug(f'Sandbox workspace: {sandbox_workspace_dir}')
  261. if self.config.sandbox.browsergym_eval_env is not None:
  262. browsergym_arg = (
  263. f'--browsergym-eval-env {self.config.sandbox.browsergym_eval_env}'
  264. )
  265. else:
  266. browsergym_arg = ''
  267. self.container = self.docker_client.containers.run(
  268. self.runtime_container_image,
  269. command=(
  270. f'/openhands/micromamba/bin/micromamba run -n openhands '
  271. f'poetry run '
  272. f'python -u -m openhands.runtime.action_execution_server {self._container_port} '
  273. f'--working-dir "{sandbox_workspace_dir}" '
  274. f'{plugin_arg}'
  275. f'--username {"openhands" if self.config.run_as_openhands else "root"} '
  276. f'--user-id {self.config.sandbox.user_id} '
  277. f'{browsergym_arg}'
  278. ),
  279. network_mode=network_mode,
  280. ports=port_mapping,
  281. working_dir='/openhands/code/', # do not change this!
  282. name=self.container_name,
  283. detach=True,
  284. environment=environment,
  285. volumes=volumes,
  286. )
  287. self.log_buffer = LogBuffer(self.container)
  288. logger.info(f'Container started. Server url: {self.api_url}')
  289. self.send_status_message('STATUS$CONTAINER_STARTED')
  290. except Exception as e:
  291. logger.error(
  292. f'Error: Instance {self.container_name} FAILED to start container!\n'
  293. )
  294. logger.exception(e)
  295. self.close(close_client=False)
  296. raise e
  297. def _attach_to_container(self):
  298. container = self.docker_client.containers.get(self.container_name)
  299. self.log_buffer = LogBuffer(container)
  300. self.container = container
  301. self._container_port = 0
  302. for port in container.attrs['NetworkSettings']['Ports']:
  303. self._container_port = int(port.split('/')[0])
  304. break
  305. self._host_port = self._container_port
  306. self.api_url = f'{self.config.sandbox.local_runtime_url}:{self._container_port}'
  307. logger.info(
  308. f'attached to container: {self.container_name} {self._container_port} {self.api_url}'
  309. )
  310. def _refresh_logs(self):
  311. logger.debug('Getting container logs...')
  312. assert (
  313. self.log_buffer is not None
  314. ), 'Log buffer is expected to be initialized when container is started'
  315. logs = self.log_buffer.get_and_clear()
  316. if logs:
  317. formatted_logs = '\n'.join([f' |{log}' for log in logs])
  318. logger.info(
  319. '\n'
  320. + '-' * 35
  321. + 'Container logs:'
  322. + '-' * 35
  323. + f'\n{formatted_logs}'
  324. + '\n'
  325. + '-' * 80
  326. )
  327. @tenacity.retry(
  328. stop=tenacity.stop_after_delay(120) | stop_if_should_exit(),
  329. wait=tenacity.wait_exponential(multiplier=2, min=1, max=20),
  330. reraise=(ConnectionRefusedError,),
  331. )
  332. def _wait_until_alive(self):
  333. self._refresh_logs()
  334. if not (self.log_buffer and self.log_buffer.client_ready):
  335. raise RuntimeError('Runtime client is not ready.')
  336. response = send_request_with_retry(
  337. self.session,
  338. 'GET',
  339. f'{self.api_url}/alive',
  340. retry_exceptions=[ConnectionRefusedError],
  341. timeout=300, # 5 minutes gives the container time to be alive 🧟‍♂️
  342. )
  343. if response.status_code == 200:
  344. return
  345. else:
  346. msg = f'Action execution API is not alive. Response: {response}'
  347. logger.error(msg)
  348. raise RuntimeError(msg)
  349. def close(self, close_client: bool = True, rm_all_containers: bool = True):
  350. """Closes the EventStreamRuntime and associated objects
  351. Parameters:
  352. - close_client (bool): Whether to close the DockerClient
  353. - rm_all_containers (bool): Whether to remove all containers with the 'openhands-sandbox-' prefix
  354. """
  355. if self.log_buffer:
  356. self.log_buffer.close()
  357. if self.session:
  358. self.session.close()
  359. try:
  360. containers = self.docker_client.containers.list(all=True)
  361. for container in containers:
  362. try:
  363. # If the app doesn't shut down properly, it can leave runtime containers on the system. This ensures
  364. # that all 'openhands-sandbox-' containers are removed as well.
  365. if rm_all_containers and container.name.startswith(
  366. self.container_name_prefix
  367. ):
  368. container.remove(force=True)
  369. elif container.name == self.container_name:
  370. if not self.skip_container_logs:
  371. logs = container.logs(tail=1000).decode('utf-8')
  372. logger.debug(
  373. f'==== Container logs on close ====\n{logs}\n==== End of container logs ===='
  374. )
  375. container.remove(force=True)
  376. except docker.errors.APIError:
  377. pass
  378. except docker.errors.NotFound:
  379. pass
  380. except docker.errors.NotFound: # yes, this can happen!
  381. pass
  382. if close_client:
  383. self.docker_client.close()
  384. def run_action(self, action: Action) -> Observation:
  385. if isinstance(action, FileEditAction):
  386. return self.edit(action)
  387. # set timeout to default if not set
  388. if action.timeout is None:
  389. action.timeout = self.config.sandbox.timeout
  390. with self.action_semaphore:
  391. if not action.runnable:
  392. return NullObservation('')
  393. if (
  394. hasattr(action, 'confirmation_state')
  395. and action.confirmation_state
  396. == ActionConfirmationStatus.AWAITING_CONFIRMATION
  397. ):
  398. return NullObservation('')
  399. action_type = action.action # type: ignore[attr-defined]
  400. if action_type not in ACTION_TYPE_TO_CLASS:
  401. return FatalErrorObservation(f'Action {action_type} does not exist.')
  402. if not hasattr(self, action_type):
  403. return FatalErrorObservation(
  404. f'Action {action_type} is not supported in the current runtime.'
  405. )
  406. if (
  407. getattr(action, 'confirmation_state', None)
  408. == ActionConfirmationStatus.REJECTED
  409. ):
  410. return UserRejectObservation(
  411. 'Action has been rejected by the user! Waiting for further user input.'
  412. )
  413. self._refresh_logs()
  414. assert action.timeout is not None
  415. try:
  416. response = send_request_with_retry(
  417. self.session,
  418. 'POST',
  419. f'{self.api_url}/execute_action',
  420. json={'action': event_to_dict(action)},
  421. timeout=action.timeout,
  422. )
  423. if response.status_code == 200:
  424. output = response.json()
  425. obs = observation_from_dict(output)
  426. obs._cause = action.id # type: ignore[attr-defined]
  427. else:
  428. logger.debug(f'action: {action}')
  429. logger.debug(f'response: {response}')
  430. error_message = response.text
  431. logger.error(f'Error from server: {error_message}')
  432. obs = FatalErrorObservation(
  433. f'Action execution failed: {error_message}'
  434. )
  435. except requests.Timeout:
  436. logger.error('No response received within the timeout period.')
  437. obs = FatalErrorObservation(
  438. f'Action execution timed out after {action.timeout} seconds.'
  439. )
  440. except Exception as e:
  441. logger.error(f'Error during action execution: {e}')
  442. obs = FatalErrorObservation(f'Action execution failed: {str(e)}')
  443. self._refresh_logs()
  444. return obs
  445. def run(self, action: CmdRunAction) -> Observation:
  446. return self.run_action(action)
  447. def run_ipython(self, action: IPythonRunCellAction) -> Observation:
  448. return self.run_action(action)
  449. def read(self, action: FileReadAction) -> Observation:
  450. return self.run_action(action)
  451. def write(self, action: FileWriteAction) -> Observation:
  452. return self.run_action(action)
  453. def browse(self, action: BrowseURLAction) -> Observation:
  454. return self.run_action(action)
  455. def browse_interactive(self, action: BrowseInteractiveAction) -> Observation:
  456. return self.run_action(action)
  457. # ====================================================================
  458. # Implement these methods (for file operations) in the subclass
  459. # ====================================================================
  460. def copy_to(
  461. self, host_src: str, sandbox_dest: str, recursive: bool = False
  462. ) -> None:
  463. if not os.path.exists(host_src):
  464. raise FileNotFoundError(f'Source file {host_src} does not exist')
  465. self._refresh_logs()
  466. try:
  467. if recursive:
  468. # For recursive copy, create a zip file
  469. with tempfile.NamedTemporaryFile(
  470. suffix='.zip', delete=False
  471. ) as temp_zip:
  472. temp_zip_path = temp_zip.name
  473. with ZipFile(temp_zip_path, 'w') as zipf:
  474. for root, _, files in os.walk(host_src):
  475. for file in files:
  476. file_path = os.path.join(root, file)
  477. arcname = os.path.relpath(
  478. file_path, os.path.dirname(host_src)
  479. )
  480. zipf.write(file_path, arcname)
  481. upload_data = {'file': open(temp_zip_path, 'rb')}
  482. else:
  483. # For single file copy
  484. upload_data = {'file': open(host_src, 'rb')}
  485. params = {'destination': sandbox_dest, 'recursive': str(recursive).lower()}
  486. response = send_request_with_retry(
  487. self.session,
  488. 'POST',
  489. f'{self.api_url}/upload_file',
  490. files=upload_data,
  491. params=params,
  492. timeout=300,
  493. )
  494. if response.status_code == 200:
  495. return
  496. else:
  497. error_message = response.text
  498. raise Exception(f'Copy operation failed: {error_message}')
  499. except requests.Timeout:
  500. raise TimeoutError('Copy operation timed out')
  501. except Exception as e:
  502. raise RuntimeError(f'Copy operation failed: {str(e)}')
  503. finally:
  504. if recursive:
  505. os.unlink(temp_zip_path)
  506. logger.info(f'Copy completed: host:{host_src} -> runtime:{sandbox_dest}')
  507. self._refresh_logs()
  508. def list_files(self, path: str | None = None) -> list[str]:
  509. """List files in the sandbox.
  510. If path is None, list files in the sandbox's initial working directory (e.g., /workspace).
  511. """
  512. self._refresh_logs()
  513. try:
  514. data = {}
  515. if path is not None:
  516. data['path'] = path
  517. response = send_request_with_retry(
  518. self.session,
  519. 'POST',
  520. f'{self.api_url}/list_files',
  521. json=data,
  522. timeout=30, # 30 seconds because the container should already be alive
  523. )
  524. if response.status_code == 200:
  525. response_json = response.json()
  526. assert isinstance(response_json, list)
  527. return response_json
  528. else:
  529. error_message = response.text
  530. raise Exception(f'List files operation failed: {error_message}')
  531. except requests.Timeout:
  532. raise TimeoutError('List files operation timed out')
  533. except Exception as e:
  534. raise RuntimeError(f'List files operation failed: {str(e)}')
  535. def copy_from(self, path: str) -> bytes:
  536. """Zip all files in the sandbox and return as a stream of bytes."""
  537. self._refresh_logs()
  538. try:
  539. params = {'path': path}
  540. response = send_request_with_retry(
  541. self.session,
  542. 'GET',
  543. f'{self.api_url}/download_files',
  544. params=params,
  545. stream=True,
  546. timeout=30,
  547. )
  548. if response.status_code == 200:
  549. data = response.content
  550. return data
  551. else:
  552. error_message = response.text
  553. raise Exception(f'Copy operation failed: {error_message}')
  554. except requests.Timeout:
  555. raise TimeoutError('Copy operation timed out')
  556. except Exception as e:
  557. raise RuntimeError(f'Copy operation failed: {str(e)}')
  558. def _is_port_in_use_docker(self, port):
  559. containers = self.docker_client.containers.list()
  560. for container in containers:
  561. container_ports = container.ports
  562. if str(port) in str(container_ports):
  563. return True
  564. return False
  565. def _find_available_port(self, max_attempts=5):
  566. port = 39999
  567. for _ in range(max_attempts):
  568. port = find_available_tcp_port(30000, 39999)
  569. if not self._is_port_in_use_docker(port):
  570. return port
  571. # If no port is found after max_attempts, return the last tried port
  572. return port
  573. def send_status_message(self, message: str):
  574. """Sends a status message if the callback function was provided."""
  575. if self.status_message_callback:
  576. self.status_message_callback(message)