eventstream_runtime.py 25 KB

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